黑马程序员_关于选择排序和冒泡排序的复习

来源:互联网 发布:办公软件mac版免费 编辑:程序博客网 时间:2024/05/14 08:12

---------------------- android培训、java培训、期待与您交流! ----------------------


/*
选择排序和冒泡排序:
内循环参与比较的元素在逐级地减少。


 思考:能否将一个字符串变成字符数组后,对该字符数组进行冒泡排序呢?
    可以的,但是有几个地方需要注意,int数组需要变为char型数组,定义的临时变量temp也必须变为char字符。


*/
class SortDemo
{
//选择排序:
public static void selectSort(int[] arr)
{
for(int x=0;x<arr.length-1; x++)
{
for(int y=x+1;y<arr.length; y++)
{
if(arr[x]>arr[y])
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}


}


//冒泡排序:
public static void bubbleSort(int[] arr)
{
for(int x=0;x<arr.length-1;x++)
{
for(int y=0;y<arr.length-x-1;y++)
{
if(arr[y]>arr[y+1])
{
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;
}
}
}
}
public static void main(String[] args)
{


int[] arr = {5,1,6,4,2,8,9};

printArray(arr);


//bubbleSort(arr);
selectSort(arr);
printArray(arr);


/*
//改int数组为char数组,temp变量也为char后可对字符数组进行冒泡排序。
String s ="hellodfworkday";


char[] chs =s.toCharArray();


printArray(chs);


bubbleSort(chs);


printArray(chs);
*/




}
public static void printArray(int[] arr)
{
System.out.print("[");
for(int x=0;x<arr.length;x++)
{
if(x!=(arr.length-1))
System.out.print(arr[x]+", ");
else
System.out.println(arr[x]+"]");
}
}
}

---------------------- android培训、java培训、期待与您交流! ----------------------

详情请查看:http://edu.csdn.net/heima