数据结构-十大经典排序算法之快速排序
- 算法思想
- 算法步骤
- 算法动态演示
- 部分代码实现
第一部分:算法思想
快速排序是最常用的一种排序算法,它的特点是速度快、效率高。快速排序的基本思想:选择一个关键值作为基准值。比基准值小的都在左边序列(一般是无序的),比基准值大的都在右边(一般是无序的)。一般选择序列的第一个元素作为基准值。
第二部分:算法步骤
从数列中挑出一个元素,称为基准pivot;
分区partition操作:比基准值小的元素放在左边,比基准值大的元素放在右边;
递归recursive:把小于基准值元素的子数列和大于基准值元素的子数列分别递归排序。
第三部分:算法动态演示
第四部分:代码实现
package study;
import java.util.Scanner;
public class QuickSort {
public static void main(String[] args) {
int count;
System.out.print("Please enter the number of Array:");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
int arr[] = new int[count];
System.out.println("Enter the numbers");
for (int i = 0; i < count ; i++) {
arr[i] = sc.nextInt();
}
System.out.println("经排序后的数组:");
long begin = System.nanoTime();
Quick_sort(arr,0,count-1);
print_Array(arr,count);
long end = System.nanoTime();
System.out.println("");
System.out.println("快速排序所耗时间:"+(end-begin)+" ns");
}
private static int getIndex(int arr[],int low,int high){
//设置基准值
int pivot = arr[low];
while(low<high){
/*如果下标high对应的值大于基准值,则将high指针往前面移*/
while(low<high&&arr[high]>=pivot){
high--;
}
//若小于则将此值赋给arr[low]
arr[low] = arr[high];
/*如果下标low对应的值小于基准值,则将lowhigh指针往后面移*/
while(low<high&&arr[low]<=pivot){
low++;
}
//若大于则将此值赋给high
arr[high] = arr[low];
}
//跳出循环则low=high即找到了对应基准值
arr[low] = pivot;
return low;
}
private static void Quick_sort(int[] arr,int low,int high){
if(low<high){
//获得基准值下标
int index = getIndex(arr,low,high);
//递归遍历前后半部分
Quick_sort(arr,low,index-1);
Quick_sort(arr,index+1,high);
}
}
private static void print_Array(int arr[],int n){
if(n==0)
System.out.println("ERROR: Array length is ZERO\\n");
else
for (int i: arr) {
System.out.print(i+" ");
}
}
}
运行结果:
- 看到这了,如果觉得有用的话动动手指点个赞吧,下期带来“数据结构-十大经典排序算法之堆排序”。