编写一个冒泡法排序程序要求在程序中能够捕获到数组下标越界的异常答案

2025-05-22 20:56:25
推荐回答(3个)
回答1:

template
bool BubSort(DataType a[], int l, int r, char z) //冒泡排序
{
int i=0;
int j=0;
DataType k;

if(z=='y')//升序排列
{
for (i=l;i<=r-1;i++)
for (j=r-1;j>=i+1;j--)
if (a[j-1]>a[j])
{
k=a[j-1];
a[j-1]=a[j];
a[j]=k;
}
}
else if(z=='n')//降序排列
{
for (i=l;i<=r-1;i++)
for (j=r-1;j>=i+1;j--)
if (a[j-1] {
k=a[j-1];
a[j-1]=a[j];
a[j]=k;
}
}
else return false;
}

冒泡排序的一个模板函数,供楼主参考!

回答2:

#include
void main()
{
int a[]=,*p=a;
int i,j,temp,size;
size=sizeof(a)/sizeof(int);
for(i=0;i{
for(j=0;j {
if(*(p+j)>*(p+j+1))
{
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
}
}
for(i=0;i cout< cout<}
上学期学的,生疏了,呵呵

回答3:

楼主试试:
public class Test {
public static void main(String[] args) {
int[] arr = new int[]{2,3,1};
for(int i=0;i for(int j=arr.length-1;j>=0;j--){
int tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
}
try{
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}