首页 > 代码库 > 冒泡排序和快速排序的Java实现

冒泡排序和快速排序的Java实现

简单说:冒泡就是两两比较,交换位置,

快速就是双向遍历交换位置,知道开始和结束处于同一位置的时候。

直接贴代码:

冒泡:

 

package com.wuyjngjie.sort;

public class MaoPao {

public static void main(String[] args) {
int[] a = { 11 ,23,33,99,56};
int c;

for (int b = 0; b <a.length - 1; b++) {
for (int m = 1; m<=a.length - 1; m++) {
if (a[m-1] < a[m]) {
c = a[m-1];
a[m-1] = a[m];
a[m] = c;
}
}
}
for (int d : a) {
System.out.print(d + ",");
}
}

}

 

快速:

package com.wuyjngjie.sort;

public class KuaiSu {

public static void main(String[] args) {
int[] shuzu = { 23, 56, 78, 45, 11, 4, 6, 8 };
int start = 0;
int end = shuzu.length - 1;
sort(shuzu, start, end);
for (int a : shuzu) {
System.out.print(a + ",");
}

}

private static void sort(int[] shuzu, int low, int high) {

int start = low;
int end = high;
int key = shuzu[low];

while (end > start) {
while (end > start && shuzu[end] > key) {
end--;
}
if (shuzu[end] < key) {
int temp = shuzu[start];
shuzu[start] = shuzu[end];
shuzu[end] = temp;
}
while (start < end && shuzu[start] < key) {
start++;
}
if (shuzu[start] > key) {
int temp = shuzu[start];
shuzu[start] = shuzu[end];
shuzu[end] = temp;
}
}
int d=0;
if(start>low){
sort(shuzu, low, start-1);
}
if(end<high){
sort(shuzu, end+1, high);
}
}

}

 

冒泡排序和快速排序的Java实现