一,冒泡排序法
public class BubbleSort {
public static long[] sort(long[] arr){
long temp;
for(int i=0;i<arr.length-1;i++){
for(int j=arr.length-1;j>i;j--){
if(arr[j]<arr[j-1]){
temp=arr[j];
arr[j] = arr[j-1];
arr[j-1]=temp;
}
}
}
return arr;
}
}
测试:
public class TestSort {
public static void main(String[] args) {
long[] arr = new long[5];
arr[0]=34;
arr[1]=23;
arr[2]=2;
arr[3]=1;
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
arr = BubbleSort.sort(arr);
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
}
}
二:选择排序
public class SelectionSort {
public static long[] sort(long[] arr){
int k=0;
long temp;
for(int i=0;i<arr.length-1;i++){
k=i;
for(int j=i;j<arr.length;j++){
if(arr[j]<arr[k]){
k=j;
}
}
temp=arr[i];
arr[i]=arr[k];
arr[k]=temp;
}
return arr;
}
}
测试:
public class TestSort {
public static void main(String[] args) {
long[] arr = new long[5];
arr[0]=34;
arr[1]=23;
arr[2]=2;
arr[3]=1;
arr[4]=-1;
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
arr = SelectionSort.sort(arr);
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
}
}
三:插入排序
public class InsertSort {
public static long[] sort(long[] arr){
long temp=0;
for(int i=1;i<arr.length-1;i++){
temp=arr[i];
int j=1;
while(j<0&&arr[j]>=temp){
arr[j]=arr[j-1];
j--;
}
arr[j]=temp;
}
return arr;
}
}
测试:
public class TestSort {
public static void main(String[] args) {
long[] arr = new long[5];
arr[0]=34;
arr[1]=23;
arr[2]=2;
arr[3]=1;
arr[4]=-1;
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
arr = InsertSort.sort(arr);
System.out.println("[");
for(long num:arr){
System.out.println(num+" ");
}
System.out.println("]");
System.out.println();
}
}