花了好长一段时间,终于把快速排序法弄懂了。

本文详细介绍了一种高效的排序算法——快速排序。通过递归的方式将数组分为较小和较大的两个子数组,并分别进行排序,最终实现整个数组的有序排列。文中提供了完整的C++实现代码,包括两种不同的快速排序实现方式及数组显示函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//快速排序法
#include<iostream>
using namespace std;

void split(int a[],int low,int high,int &i)
{//a[]为2 8 3 6 9 5 1 4 0 7
   i=low;
  int j=high;
  int x=a[i];
  while(i<j)
    {
//目标:x=2, a[]=2 8 3 6 9 5 1 4 0 7
//=>x=2, a[]=0 1 2 6 9 5 3 4 8 7
      while(x<=a[j] && i<j)
    j--;
      if(i<j)
    {
      a[i]=a[j];
      i++;
    }

      while(x>a[i] && i<j)
    i++;
      if(i<j)
    {
      a[j]=a[i];
      j--;
    }
    }
    a[i]=x;


}
void qsort(int a[],int s,int t)
{

  int i;
  if(s<t)
    {

  split(a,s,t,i);
  qsort(a,0,i-1);
  qsort(a,i+1,t);
  //      cout<<a[i]<<" ";
    }
}
void qsort1(int a[],int n)
{
  qsort(a,0,n-1);
}
void qsort2(int a[],int n)
{
  int stack[100][2];
  int i;
  int j,k;
  int top=0;
  stack[top][0]=0;
  stack[top][1]=n-1;
  while(top>=0)
    {
      j=stack[top][0];
      k=stack[top][1];
      top--;
      split(a,j,k,i);
      if(j<k)
    {
      top++;
      stack[top][0]=j;
      stack[top][1]=i-1;
      top++;
      stack[top][0]=i+1;
      stack[top][1]=k;

    }

    }
  cout<<endl;

}
void display(int a[],int n)
{
  for(int i=0;i<n;i++)
    {
      cout<<a[i]<<" ";
    }
}
int main()
{
  int a[]={2,8,3,6,9,5,1,4,0,7};
  int n=10;
  //  int i;
   qsort1(a,n);
  //    display(a,n);
  //  cout<<endl;
  // split(a,0,n-1,i);
   //  cout<<endl;
     display(a,n);
     qsort2(a,n);
     display(a,n);
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值