使用冒泡排序
代码
package com.qixin.five;
public class BubbleSort {
public static void main(String[] args) {
int[] array = new int[]{5,1,2,8,4,6,9,7,3,0};
int temp;
System.out.println("原有数组内容:");
printArray(array);
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length-i; j++) {
if(array[j]>array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
System.out.println("从小到大排序后的结果:");
printArray(array);
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length-i; j++) {
if(array[j]<array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
System.out.println("从大到小排序后的结果:");
printArray(array);
}
public static void printArray(int array[]){
for(int i:array){
System.out.print(i+" ");
}
System.out.println("\n");
}
}
使用选择排序
代码
package com.qixin.five;
public class SelectSort {
public static void main(String[] args) {
int[] array = new int[]{5,1,2,8,4,6,9,7,3,0};
int temp;
System.out.println("原有数组内容:");
printArray(array);
int index;
for (int i = 1; i < array.length; i++) {
index=0;
for (int j = 1; j <= array.length-i; j++) {
if(array[j]>array[index]){
index=j;
}
}
temp=array[array.length-i];
array[array.length-i]=array[index];
array[index]=temp;
}
System.out.println("正序排列数组内容:");
printArray(array);
for (int i = 1; i < array.length; i++) {
index=0;
for (int j = 1; j <= array.length-i; j++) {
if(array[j]<array[index]){
index=j;
}
}
temp=array[array.length-i];
array[array.length-i]=array[index];
array[index]=temp;
}
System.out.println("倒序排列数组内容:");
printArray(array);
}
public static void printArray(int[] array){
for(int i:array){
System.out.print(i+" ");
}
}
}