各种排序算法_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 各种排序算法

各种排序算法

 2012/3/28 17:29:41  jdkleo  程序员俱乐部  我要评论(0)
  • 摘要:冒泡排序:int[]a={345,7,32,5,4,7};for(inti=0;i<a.length-1;i++){for(intj=i+1;j<a.length;j++){if(a[i]>a[j]){inttemp=a[i];a[i]=a[j];a[j]=temp;}}}for(inti=0;i<a.length;i++){System.out.println(a[i]);}快速排序(无重复值):publicclassSortTest
  • 标签:算法
冒泡排序
int[] a = {345,7,32,5,4,7};
for (int i = 0; i < a.length-1; i++) {
	for (int j = i+1; j < a.length; j++) {
		if (a[i]>a[j]){
			int temp = a[i];
			a[i] = a[j];
			a[j] = temp;
		}
	}
}
for (int i = 0; i < a.length; i++) {
	System.out.println(a[i]);
}

快速排序(无重复值):
public class SortTest {
	public static void main(String[] args) {
		int[] a = {345,7,32,5,4,3,12,23,110};
		show(a);
		quickSort(a,0,a.length-1);
		show(a);
	}

	private static void quickSort(int[] a, int start, int end) {
		if (start>=end)
			return;
		int i=start;
		int j=end;
		int index = start;
		while(i<j){
			while(a[j]>a[index]){
				j--;
			}
			index = swap(a,j,index);
			while(a[index]>a[i]){
				i++;
			}
			index = swap(a,i,index);
		}
		quickSort(a, start, index-1);
		quickSort(a, index+1, end);
	}

	private static int swap(int[] a, int n, int index) {
		int tmp = a[n];
		a[n] = a[index];
		a[index] = tmp;
		return n;
	}

	private static void show(int[] a) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i]);
			if (i!=a.length-1){
				System.out.print("\t");
			}else{
				System.out.println();
			}
		}
	}
	
}

快速排序(可含重复值)
public class SortTest {
	public static void main(String[] args) {
		int[] a = {345,7,32,5,4,-1,3,12,23,110,45645,321,456,78,-1,78,78,32,345};
		show(a);
		quickSort2(a,0,a.length-1);
		show(a);
	}
	
	private static void quickSort2(int[] a, int start, int end) {
		if (start>=end)
			return;
		int i=start;
		int j=end;
		int index = end;
		while(i<j){
			while(a[j]>a[index]){
				j--;
			}
			if (j!=index && a[j]==a[index]){
				index = swap(a,--j,index);
			}else{
				index = swap(a,j,index);
			}
			while(a[index]>a[i]){
				i++;
			}
			if (i!=index && a[i]==a[index]){
				index = swap(a,++i,index);
			}else{
				index = swap(a,i,index);
			}
		}
		quickSort2(a, start, index-1);
		quickSort2(a, index+1, end);
	}

	private static int swap(int[] a, int n, int index) {
		int tmp = a[n];
		a[n] = a[index];
		a[index] = tmp;
		return n;
	}

	private static void show(int[] a) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i]);
			if (i!=a.length-1){
				System.out.print("\t");
			}else{
				System.out.println();
			}
		}
	}
}
发表评论
用户名: 匿名