快速排序算法及实现

第一篇博客,好激动emmm。
言归正传,这篇博客是我对《算法导论》上快速排序算法的实践与一些思考。
首先贴出快速排序的坑爹的伪代码:

QuickSort(A,p,r)
  if p<r
      q = Partition(A,p,r)    
      QuickSort(A,p,q-1)     
      QuickSort(Q,q+1,r)     
 end

Partition(A,p,r) 
  x = A[r]   
  i = p-1 
  for  j = p  to  r-1    
      if  A[j] <= x
          i = i+1 
          exchange A[i] <-> A[j]
  exchange A[i+1]<->A[r]   
  return i+1   
end

之后贴出对应的c++代码:

#include "stdafx.h"
#include<iostream>
#define N   10
using namespace std;

void quicksort(int A[], int low, int high);
int partition(int A[], int low, int high);

int main()
{
    int A[N];
    cout << "input ten number" << endl;
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }
    quicksort(A,0,N-1);
    for (int i = 0; i < N; i++) {
        cout << A[i] <<" ";
    }
    cout << endl;
    return 0;
}

int partition(int A[], int low, int high){
    int x = A[high];
    int first = low - 1;
    int temp;
    for (int last = low; last < high; last++) {
        if (A[last] <= x) {
            first = first + 1;
            temp = A[first];
            A[first] = A[last];
            A[last] = temp;
        }       
    }
    temp = A[first + 1];
    A[first + 1] = A[high];
    A[high] = temp;
    return first+1;
}

void quicksort(int A[], int low, int high) {
    if (low < high)
    {
        int middle = partition(A, low, high);
        quicksort(A, low, middle - 1);
        quicksort(A, middle + 1, high);
    }
}

这里开始考虑代码中出现的问题:
1.虽然快速排序很简单,但是从伪代码到C++源代码需要注意这几点:
每个缩进代表一个函数的函数体具体内容。
注意for(;;)循环之后,循环变量值保持不变,循环变量最终值为“循环变量+1”
2.考虑函数中几个>=号,这几个符号我认为是由于快速排序具有不稳定性。因此可能出现low>=high的情况,另外low==high的确为判定结束的标志。
3.cin与scanf()相比,减少了指针“崩”的情况,C++大法好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值