码迷,mamicode.com
首页 > 编程语言 > 详细

七大排序之快排(重点 面试基本都会问)

时间:2020-05-30 22:16:02      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:strong   art   font   rand   不能   struct   key   while   分治法   

必须要明白的: 分治法+挖坑填数;

分治法:大问题分解成各个小问题,对小问题求解,使得大问题得以解决。

 

 1 #include<iostream>
 2 #include<time.h>
 3 #include<stdlib.h>
 4 #include<sys/timeb.h>
 5 using namespace std;
 6 
 7 const int Max = 10;
 8 
 9 void swap(int& a, int& b) {
10     int temp = a;
11     a = b;
12     b = temp;
13 }
14 
15 long getSystemTime() {
16     struct timeb tb;
17     ftime(&tb);
18     return tb.time * 1000 + tb.millitm;
19 }
20 void Print(const int* arr, int length) {
21     for (int i = 0; i < length; i++) {
22         cout << arr[i] << " ";
23     }
24 }
25 void QuickSort(int* arr, int start, int end) {
26     int i = start;
27     int j = end;
28     //这里注意key不能为arr[0];
29     int key = arr[start];
30     if (i < j) {
31         while (i < j) {
32             while (i < j && arr[j] >= key) {
33                 j--;
34             }
35             if (i < j) {
36                 arr[i] = arr[j];
37                 i++;
38             }
39             while (i < j && arr[i] < key)
40             {
41                 i++;
42             }
43             if (i < j) {
44                 arr[j] = arr[i];
45                 j--;
46             }
47         }
48         //下面三行代码不能放在if语句的外面
49         arr[i] = key;
50         QuickSort(arr, start, i - 1);
51         QuickSort(arr, i + 1, end);
52     }
53 
54 }
55 
56 int main() {
57     int arr[Max];
58     srand((unsigned)time(NULL));
59     for (int i = 0; i < Max; i++) {
60         arr[i] = rand() % Max;
61     }
62     cout << "排序前:\n";
63     Print(arr, Max);
64     long pt = getSystemTime();
65     QuickSort(arr, 0, Max - 1);
66     long at = getSystemTime();
67     cout << "\n排序后:\n";
68     Print(arr, Max);
69 
70     cout << "\ntime of sort:" << at - pt << "ms\n";
71 
72 
73     return 0;
74 }

 

七大排序之快排(重点 面试基本都会问)

标签:strong   art   font   rand   不能   struct   key   while   分治法   

原文地址:https://www.cnblogs.com/jibisheng/p/12994886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!