⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 quicksort.cpp

📁 一个写在vc中的快速排序法函数
💻 CPP
字号:
#include "stdafx.h"
#include "iostream.h"

void swap(int *a,int low,int high);
void QuickSort(int *a,int st,int ed);
void output(int *a,int low,int high);

void swap(int *a,int low,int high)
{
 int temp=a[low];
 a[low]=a[high];
 a[high]=temp;
}

void QuickSort(int *a,int st,int ed)
{
 int balance=(a[st]+a[ed])/2;
 int low=st;
 int high=ed;
 while(low<high)
 {
   while(a[high]>=balance)  high--;    
   while(a[low]<=balance) low++;
   if(low<high)
     swap(a,low,high);
   if(high==st-1)      
   /*考虑特殊情况,当balance的值为最小值时high会滑出当前st-ed的
     范围变为st-1,此时仅当a[st]>a[ed]时才才需要交换,比如a{0,1},
     因为while的的循环条件以及下面low和high的值要交换,将low和high
     的值颠倒*/
   {  
     if(a[st]>a[ed]) 
       swap(a,st,ed);      
     high=st; 
     low=st+1;                
   }
   //output(a,low,high);
 }    
 int t=low;
 low=high;
 high=t;        
 if(low>=st+1) 
   QuickSort(a,st,low);
 if(high<=ed-1)
   QuickSort(a,high,ed);  
}

void output(int *a,int low,int high)
{
 for(int i=low;i<=high;i++)
   cout<<a[i]<<" ";
 cout<<endl;  
}

void main()
{
 int arr[15]={1111,4,3,45,454,2,4,56,6,34,1,231,45,63,0};  
 QuickSort(arr,0,14);  
 output(arr,0,14);
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -