Java 各种排序算法

时间:2023-02-04 22:10:25

从网上看了很多排序,

方式算法不一,

一头雾水,

所以简单整理了几个算法。

供大家参考。

1.冒泡排序: 

 

public static void main(String[] args) throws Exception {
new Test().mao_pao_sort();//冒泡排序
}

public void mao_pao_sort() {
int[] arras = { 3, 4, 1, 5, 32, 11, 42, 51, 0 };
int temp = 0;
for (int i = 0; i < arras.length; i++) {
for (int j = 0; j < arras.length - i - 1; j++) {

if (arras[j] > arras[j + 1]) {
temp = arras[j];
arras[j] = arras[j + 1];
arras[j + 1] = temp;
}
}
}

for (int i = 0; i < arras.length; i++) {
System.out.print(arras[i] + " ");

}
}

 

2.利用Arrays自带Sort进行排序:

/**
* @param args
*/
public static void main(String[] args) {

int []arrs={3,4,5,5,67,2,4};
Arrays.sort(arrs);
for (int i = 0; i < arrs.length; i++) {
System.out.println(arrs[i]);
}
}

 

3.选择排序算法

/**
* @param args
*/
public static void main(String[] args) {
int[] arras={1,3,6,3,2};

for (int i = 0; i < arras.length; i++) {
int num=i;
for (int j = i+1; j < arras.length; j++) {
if(arras[num]>arras[j]){
num=j;
}
}

if(num!=i){
int temp=arras[i];
arras[i]=arras[num];
arras[num]=temp;
}

}


for (int i = 0; i < arras.length; i++) {
System.out.println(arras[i]);
}
}


 

4.插入排序算法:

 

public static void main(String[] args) throws Exception {
int[] arras = { 3, 4, 1, 5, 32, 11, 42, 51, 0 };
new Test().mao_pao_sort(arras);
for (int i = 0; i < arras.length; i++) {
System.out.println(arras[i]);
}
}

public void mao_pao_sort(int []arras) {

for (int i = 0; i < arras.length; i++) {
for (int j = i; j > 0;j--) {
if(arras[j]<arras[j-1]){
int temp=arras[j];
arras[j]=arras[j-1];
arras[j-1]=temp;
}
}
}

}