以下都是按升序排序。
简单选择排序:
public void sort(int[] array)
{
int temp=0;
for(int i=0;i<array.length-1;i++)//n-1次
{
for(int j= i+1;j<array.length;j++)
{
if(array[j]<array[i])//第i个与其它各个比较
{
temp = array[j];
array[j] = array[i];
array[i]= temp;
}
}
}
}
public static void main(String[] args)
{
SimpleSort sort = new SimpleSort();
int array[] = { 4, 5, 6, 8, 15, 1, 2, 2, 7 };
sort.sort(array);
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
冒泡排序:
public static void main(String[] args)
{
SimpleSort sort = new SimpleSort();
int array[] = { 4, 5, 6, 8, 15, 1, 2, 2, 7 };
sort.bubbleSort(array);
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
public void bubbleSort(int[] array)
{
int temp = 0;
for (int i = 0; i < array.length-1; i++)//总共n-1趟排序
{
for (int j = 0; j < array.length - 1 - i; j++)//区间逐步缩小
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1]= temp;
}
}
}
}