C++ 快速排序、去重

C++ 快速排序、去重

快速排序的C++代码及详细注释如下
欢迎交流

运用分治的思想 将问题分为多个子问题
运用递归的方法
细节见注释

#include<iostream>
using namespace std;
//交换函数
template<typename T>
void swa(T&a,T&b)
{
    
    
 T temp=a;
 a=b;
 b=temp;
 return;
}
//快排  分治思想
template<typename T>
void quick(T*a,int start,int end)
{
    
    
 if(start>=end)
  return;
 T mid=a[end];//选数组最后一个数作为参照
 int left=start;//实参start作为左端
 int right=end-1;//实参end-1作为右端
 while(left<right)//遍历
 {
    
    
  while(a[left]<=mid&&left<right)//保证比mid值小的在左端
  {
    
    
   left++;
  }
  while(a[right]>=mid&&left<right)//比mid值大的在右端
  {
    
    
   right--;
  }
  swa(a[left],a[right]);//当上述两个while循环结束时,说明left==right 或者left的当前值比mid大,right的当前值比mid小,不论怎样 我们做一次交换 就能保住比mid小的任然在左边 大的任然在左边
 }
 if(a[left]>=a[end])//left==right时 找到mid位置 这时比较left和end end小的话则交换
  swa(a[left],a[end]);
 else left++;//end大的情况说明情况比较极端 说明end值为当前序列最大值 故让left自增1
 quick(a,start,left-1);//递归
 quick(a,left+1,end);//递归
}
template<typename T>
int delsame(T*a,int length)
{
    
    
 T temp;
 temp=a[0];//作为当前需要比较的中间值
 int k=1;
 for(int i=1;i<length;i++)
 {
    
    
  if(a[i]!=temp)
  {
    
    
   a[k]=a[i];//覆盖
   k++;//下标自增
   temp=a[i];//更新中间值
  }
 }
 return k;//返回覆盖后 去重后的长度
}
int main()
{
    
    
 int n;
 cout<<"输入需要排序的数列大小:";
 cin>>n;
 int *a=new int[n];
 cout<<"输入需要排序数列:";
 for(int i=0;i<n;i++)
 {
    
    
  cin>>a[i];
 }
 quick(a,0,n-1);
 cout<<"排序后的数列为:";
 for(int i=0;i<n;i++)
  cout<<a[i]<<" ";
 cout<<endl;
 int k=delsame(a,n);
 cout<<"去重后数列为:";
 for(int i=0;i<k;i++)
  cout<<a[i]<<" "; 
 cout<<endl;
 return 0;
}
输入需要排序的数列大小:10
输入需要排序数列:2 6 9 4 5 1 8 9 -7 8
排序后的数列为:-7 1 2 4 5 6 8 8 9 9
去重后数列为:-7 1 2 4 5 6 8 9

猜你喜欢

转载自blog.csdn.net/weixin_46566957/article/details/109105169