您的位置:首页 > 编程语言 > Java开发

Java各种排序算法实现与探讨

2009-09-20 23:23 246 查看
package sort;

import java.util.Random;

public class Sort {

/**
* 各种排序算法实现
*
* @param args
*/
/*
* 交换两个数,不能设计成swap(int a,int b);因为Java采用的是值传递
* 实参传给形参的是值,形参在交换方法调用完后被回收,而实参的值没变
*/
private static void swap(int a[], int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// 冒泡排序
public static void bubbleSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = a.length - 1; j > i; j--) {
if (a[j] < a[j - 1]) {
swap(a, j, j - 1);
}
}
}
}

// 插入排序
public static void insertSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < i; j++) {
if (a[i] < a[j]) {
swap(a, i, j);
}
}
}
}

// 选择排序
public static void selectSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[i]) {
swap(a, i, j);
}
}
}
}

// 快速排序
public static void quickSort(int[] a,int low, int high){
int temp,i,j;
i = low;
j = high;
temp = a[i];
//if条件跳出递归
if(i<j && low<=i && i<=high && low<=j && j<=high){
while(j>i){
//while中的条件保证数组中有重复元素时也能正常排序,如果用a[j]>temp
//当有重复元素时,由于i<j,但是i和j都不递增而造成死循环。后面加上j>i
//是保证j不会小于i,从而避免j向前多走一位的情况
while(a[j]>=temp && j>i){
j--;
}
if(i<j){
swap(a,i,j);
}

while(a[i]<=temp && j>i){
i++;
}
if(i<j){
swap(a,i,j);
}

}

//加是上条件保证递归停止
if(j-1 >= low)quickSort(a,low, j-1);
if(i+1 <= high)quickSort(a,i+1, high);
}
}

// 打印数组
public static void print(int[] a) {
for (int i = 0; i < a.length; i++) {
if (i != a.length - 1) {
System.out.print(a[i] + ",");
} else {
System.out.println(a[i]);
}
}
}

// 随机创建一个长度为n的数组
public static int[] createArray(int n) {
int[] a = new int
;
for (int i = 0; i < n; i++) {
a[i] = new Random().nextInt(100);
}
return a;
}

public static void main(String[] args) {
int[] a = Sort.createArray(10);
System.out.print("原数组:");
Sort.print(a);
Sort.bubbleSort(a);
System.out.print("冒泡排序后的数组:");
Sort.print(a);
a = Sort.createArray(10);
System.out.print("原数组:");
Sort.print(a);
Sort.insertSort(a);
System.out.print("插入排序后的数组:");
Sort.print(a);
a = Sort.createArray(10);
System.out.print("原数组:");
Sort.print(a);
Sort.insertSort(a);
System.out.print("选择排序后的数组:");
Sort.print(a);
a = Sort.createArray(10);
System.out.print("原数组:");
Sort.print(a);
Sort.quickSort(a, 0, a.length-1);
System.out.print("快速排序后的数组:");
Sort.print(a);
}

}

结果:

原数组:23,23,7,68,1,49,83,50,41,31
冒泡排序后的数组:1,7,23,23,31,41,49,50,68,83
原数组:14,32,82,75,99,82,88,73,64,96
插入排序后的数组:14,32,64,73,75,82,82,88,96,99
原数组:87,68,0,62,95,54,87,77,69,11
选择排序后的数组:0,11,54,62,68,69,77,87,87,95
原数组:30,32,67,58,49,91,83,73,75,96
快速排序后的数组:30,32,49,58,67,73,75,83,91,96
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: