交换排序的主要两种方式是冒泡排序和快速排序
冒泡排序是通过相邻的数据元素的交换,逐步将排序序列变成有序序列的过程。
下面是冒泡的例子,其中用到了控制标识来加速冒泡排序。
package sort;
import java.util.Random;
/**
* 冒泡排序
* @author longkun.wyb
*
*/
public class BubbleSort {
public static Random rand = new Random();
public static int TOTAL = rand.nextInt(100001)+1;
public static int RANDINT = rand.nextInt(1000000)+1;
public static int[] array;
public static void init(){
array =new int[TOTAL];
for(int i = 0 ; i < TOTAL ; ++i){
array[i] = rand.nextInt(RANDINT);
}
}
public static void bubble(int[] arr , int len){
boolean change = true;//判断是否排序结束
for(int i = 1 ; i < len && change ; i++){
change = false;
for(int j = len-1 ; j > i-1 ; j--){
if(arr[j] < arr[j-1]){
int tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
change = true;
}
}
}
}
public static void main(String[] args) {
System.out.println("BubbleSort");
init();
long start = System.currentTimeMillis();
bubble(array,TOTAL);
System.out.println("bubbleSort运行时间:"+(System.currentTimeMillis()-start));
for(int i = 0; i < 10;++i){
if(i % 10 == 0){
System.out.println();
}
System.out.print(array[i]+" ");
}
}
}
快速排序是通过两个(不相邻的)元素的交换,消除待排序记录中的多个逆序,而加快排序的速度。
快速排序的例子:
package sort;
import java.util.Random;
/**
* 快速排序
* @author longkun.wyb
*
*/
public class QuickSort {
public static int TOTAL = new Random().nextInt(10000001);
public static int RANDINT = new Random().nextInt(1000000000);
public static int sortOne(int[] list,int begin , int end){
// System.out.println("sortOne...");
int low = begin ;
int high = end;
int tmp = list[begin];
while(low < high){//这其中的每一个low<high是必须的
while(low < high && tmp <= list[high]){//这个"="还是非常关键的,例如2,2时这个总返回后面那个2的编号,从而进入死循环
high--;
}
if(low < high){
list[low] = list[high];
low++;
}
while(low<high && tmp > list[low]){
low++;
}
if(low < high) {
list[high] = list[low];
high--;
}
}
list[low] = tmp;
return low;
}
public static void Quick(int[] array ,int begin , int end){
if(begin < end){
int middle = QuickSort.sortOne(array, begin, end);
QuickSort.Quick(array, begin, middle);
QuickSort.Quick(array, middle+1, end);
}
}
public static void main(String[] args) throws Exception {
System.out.println("QuickSort");
Random rand = new Random();
int[] array = new int[TOTAL];
for(int i = 0 ; i < TOTAL; ++i){
array[i] = rand.nextInt(RANDINT);
// System.out.println(i+":"+array[i]+ " ");
}
long start = System.currentTimeMillis();
QuickSort.Quick(array, 0, TOTAL-1);
System.out.println("总共用时:"+ (System.currentTimeMillis()-start));
System.out.println("\n\r排序结果:");
for(int i = 0; i < 10;++i){
if(i % 10 == 0){
System.out.println();
}
System.out.print(array[i]+" ");
}
}
}