java经典算法之快速排序
2016-09-23 20:09
148 查看
举个例子
如无序数组[6,2,4,1,7,9,10,3,11,23,5]
先把第一项[6]取出来,
用[6]依次与其余项进行比较,
如果比[6]小就放[6]前边,2,4,1,7,3,5都比[6]小,所以全部放到[6]前边
如果比[6]大就放[6]后边,9比[6]大,放到[6]后边,//6出列后大喝一声,比我小的站前边,比我大的站后边,行动吧!霸气十足~
一趟排完后变成下边这样:
排序前 6,2,4,1,7,9,10,3,11,23,5
排序后 2,4,1,7,3,5,6,9,10,11,23
然后6前半部分和后半部分进行同样的操作(迭代进行)
排序结束
代码:
package algorithn;
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
private static Random random;
public static void main(String[] args) {
int[] arrint =
{6,2,4,1,7,9,10,3,11,23,5};
int start = 0 ;
int end = arrint.length;
sort(arrint,start,end -
1);
for (int i : arrint) {
System.out.println(i);
}
}
public static void qsort(int[] a){
sort(a,0,a.length - 1);
}
public static void sort(int[] aint,int start,int
end){
if(start >=end){
return;
}
int index = 0;
swap(aint,index,end);
index = start ;
for(int i = start;i <
end;i++ ){
if(aint[i]
< aint[end]){
swap(aint,index,i);
index++;//理解index的位置
}
}
swap(aint,index,end);
sort(aint,index + 1,end);
sort(aint,start,end - 1);
}
public static void swap(int[] arr,int a,int
b){
if(a == b ){
return;
}
arr[a] ^= arr[b];
arr[b] ^= arr[a];
arr[a] ^= arr[b];
}
}
如无序数组[6,2,4,1,7,9,10,3,11,23,5]
先把第一项[6]取出来,
用[6]依次与其余项进行比较,
如果比[6]小就放[6]前边,2,4,1,7,3,5都比[6]小,所以全部放到[6]前边
如果比[6]大就放[6]后边,9比[6]大,放到[6]后边,//6出列后大喝一声,比我小的站前边,比我大的站后边,行动吧!霸气十足~
一趟排完后变成下边这样:
排序前 6,2,4,1,7,9,10,3,11,23,5
排序后 2,4,1,7,3,5,6,9,10,11,23
然后6前半部分和后半部分进行同样的操作(迭代进行)
排序结束
代码:
package algorithn;
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
private static Random random;
public static void main(String[] args) {
int[] arrint =
{6,2,4,1,7,9,10,3,11,23,5};
int start = 0 ;
int end = arrint.length;
sort(arrint,start,end -
1);
for (int i : arrint) {
System.out.println(i);
}
}
public static void qsort(int[] a){
sort(a,0,a.length - 1);
}
public static void sort(int[] aint,int start,int
end){
if(start >=end){
return;
}
int index = 0;
swap(aint,index,end);
index = start ;
for(int i = start;i <
end;i++ ){
if(aint[i]
< aint[end]){
swap(aint,index,i);
index++;//理解index的位置
}
}
swap(aint,index,end);
sort(aint,index + 1,end);
sort(aint,start,end - 1);
}
public static void swap(int[] arr,int a,int
b){
if(a == b ){
return;
}
arr[a] ^= arr[b];
arr[b] ^= arr[a];
arr[a] ^= arr[b];
}
}
相关文章推荐
- Java(.NET)经典排序算法之快速排序
- 白话经典算法系列之六 快速排序 快速搞定
- 经典算法:快速排序
- 几种常见排序算法之Java实现(插入排序、希尔排序、冒泡排序、快速排序、选择排序、归并排序)
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- java 合并排序算法、冒泡排序算法、选择排序算法、插入排序算法、快速排
- java基础知识之 算法 【冒泡排序】【快速排序】
- java经典算法_025对随机生成的100以内的10个数进行排序
- 【经典算法】第一回:快速排序
- MoreWindows 专注于Windows编程 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定