</pre><pre name="code" class="cpp">#include <iostream>
using namespace std;
void quickSort(int arr[], int i, int j)
{
int i1 = i;
int i2 = j;
if(i < j)
{
int tmp = arr[i];
while(i < j)
{
while(arr[j] >= tmp && i < j)
j--;
if(i < j)
arr[i++] = arr[j];
while(arr[i] <= tmp && i < j)
i++;
if(i < j)
arr[j--] = arr[i];
}
arr[i] = tmp;
quickSort(arr, i1, i - 1);
quickSort(arr, i + 1, i2);
}
}
void adjustDown(int arr[], int end, int pos)
{
int tmpSwap = arr[pos];
int i = pos*2+1;
while (i <= end)
{
if((i < end) && (arr[i+1] < arr[i]))
++i;
if(arr[i] > tmpSwap)
break;
arr[pos] = arr[i];
pos = i;
i = pos*2+1;
}
arr[pos] = tmpSwap;
}
void BuidHeap(int arr[], int len)
{
if(len <= 1)
return;
int i = len/2 -1;
while(i>=0)
{
adjustDown(arr, len - 1, i);
i--;
}
}
void SortHeap(int arr[], int len)
{
BuidHeap(arr, len);
for(int i = 0; i < len; i++)
cout << arr[i] << " " ;
cout << endl;
int pos = len - 1;
int tmpSwap;
while(pos)
{
tmpSwap = arr[0];
arr[0] = arr[pos];
arr[pos] = tmpSwap;
adjustDown(arr,pos - 1,0);
--pos;
}
}
int main()
{
int arr[] = {2,3, 4 ,2, 5 ,76, 23, 2 ,3 ,4};
for(int i = 0; i < 10; i++)
cout << arr[i] <<" ";
cout << endl;
SortHeap(arr, 10);
for(int i = 0; i < 10; i++)
cout << arr[i] << " " ;
cout << endl;
int i;
cin >> i;
}
快速 和堆 排序算法
最新推荐文章于 2021-05-09 12:17:05 发布