the realization of quick sort in array

The results:

The original values in array a:
The number of 1 is 19
The number of 2 is 6
The number of 3 is 7
The number of 4 is 12
The number of 5 is 4
The number of 6 is 13
The number of 7 is 20
The number of 8 is 11
The number of 9 is 11
The number of 10 is 3
The number of 11 is 15
The number of 12 is 11
The number of 13 is 13
The number of 14 is 10
The number of 15 is 8
The number of 16 is 2
The number of 17 is 2
The number of 18 is 10
The number of 19 is 10
The number of 20 is 20
The sorted values in array a:
The number of 1 is 2
The number of 2 is 2
The number of 3 is 3
The number of 4 is 4
The number of 5 is 6
The number of 6 is 7
The number of 7 is 8
The number of 8 is 10
The number of 9 is 10
The number of 10 is 10
The number of 11 is 11
The number of 12 is 11
The number of 13 is 11
The number of 14 is 12
The number of 15 is 13
The number of 16 is 13
The number of 17 is 15
The number of 18 is 19
The number of 19 is 20
The number of 20 is 20

The codes:

#include <iostream>
#define MAXN 20
#include <ctime>
#include <cstdlib>
void createArry(int a[]);
using namespace std;
void quickSort(int a[], int low, int high);
void printArray(int a[]);
int main()
{
    srand((unsigned)time(NULL));
    int a[MAXN];
    createArry(a); //create an array randomly
    cout << "The original values in array a:" <<endl;
    printArray(a);
    quickSort(a, 0, MAXN-1);
    cout << "The sorted values in array a:" <<endl;
    printArray(a);
    return 0;
}
void createArry(int a[])
{
    for(int i=0; i<MAXN; ++i){
        a[i] = rand()%20 +1;
    }
}
void quickSort(int a[], int low, int high)
{
    int left_value = low;
    int right_value = high;
    if(low < high){
        int pivot_position =0;
        int pivot = a[low];
        while(low < high){
            while(low <high && a[high] >= pivot){
                --high;
            }
            a[low] = a[high];
            while(low <high && a[low] <= pivot){
                ++low;
            }
            a[high] = a[low];
        }
        a[low] = pivot;
        pivot_position = low;
        quickSort(a, left_value, pivot_position-1);
        quickSort(a, pivot_position+1, right_value);
    }else{
        return;
    }
}
void printArray(int a[])
{
    int i;
    for(i=0; i<MAXN; ++i){
        cout<< "The number of " << i+1 << " is " << a[i]<< endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值