1. 建堆
#include <stdio.h>
void swap(int *a, int *b);
//维护堆的性质
void AdjustHeap(int a[], int heap_size, int i)
{
int left = 2 * i + 1;
int right = left + 1;
//if (i == 0) {
//left = 1;
//right = 2;
//}
int largest = i;
if (left < heap_size && a[left] > a[i])
largest = left;
if (right < heap_size && a[right] > a[largest])
largest = right;
if (largest != i) {
swap(&a[largest], &a[i]);
AdjustHeap(a, heap_size, largest);
}
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
//堆排序
void heap_sort(int arr[], int heap_size) {
int i;
for(i = heap_size-1; i > 0; --i) {
swap(&arr[0], &arr[i]);
printf("%d\n", arr[i]);
--heap_size;
AdjustHeap(arr, heap_size, 0);
}
}
void print_arr(int a[], int len)
{
int i = 0;
for (i = 0; i < len; i++)
{
printf("%d\n", a[i]);
}
printf("\n");
}
int main()
{
int a[] = {0, 16, 4, 10, 14, 7, 9, 3, 2, 8, 1};
//int a[] = {16, 4, 10, 14, 7, 9, 3, 2, 8, 1};
int i = 5;
for (i = 5; i >= 0; i--)
{
AdjustHeap(a, 11, i);
}
heap_sort(a, 11);
//print_arr(a, 11);
return 0;
}
2. 快排
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int partition(int arr[], int p, int r) {
int x = arr[r];
int i = p - 1;
for (int j = p; j <= r - 1; ++j) {
if (arr[j] <= x) {
i = i +1;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[r]);
return i + 1;
}
void quickSort(int arr[], int p, int r) {
if (p < r) {
int q = partition(arr, p, r);
quickSort(arr, p, q - 1);
quickSort(arr, q + 1, r);
}
}
int main(int argc,char *argv[])
{
int arr[] = {3, 7, 2, 1, 4, 9};
quickSort(arr, 0, 5);
for (int i = 0; i < 6; ++i)
{
cout << arr[i] << endl;
}
return 0;
}