基本排序算法

void insert_sort(int a[], int length)
{
for (int i = 1; i < length; ++i)
{
int k = a[i];
int j = i - 1;

while (j >= 0 && a[j] > k)
{
a[j + 1] = a[j];
--j;
}
a[j + 1] = k;
}
}

void bubble_sort(int a[], int length)
{
for (int i = 0; i < length - 1; ++i)
{
for (int j = length -1 ; j >= i + 1; --j)
{
if (a[j - 1 ] > a[j])
{
int k = a[j - 1];
a[j - 1] = a[j];
a[j] = k;
}
}
}
}

void merge(int a[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int* L = new int[n1 + 1];
int* R = new int[n2 + 1];

memcpy(L, a + p, sizeof(int) * n1);
memcpy(R, a + q + 1, sizeof(int) * n2);

L[n1] = INT_MAX;
R[n2] = INT_MAX;

int i = 0;
int j = 0;

for (int k = p; k <= r; ++k)
{
if (L[i] <= R[j])
{
a[k] = L[i++];
}
else
{
a[k] = R[j++];
}
}

delete []L;
delete []R;
}

void merge_sort(int a[], int p , int r)
{
if (p < r)
{
int q = (p + r) / 2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
merge(a, p, q, r);
}
}

void max_heapify(int a[], int heap_size, int i)
{
int l = 2 * i;
int r = 2 * i + 1;
int largest;

if (l <= heap_size - 1 && a[l] > a[i])
{
largest = l;
}
else
largest = i;

if (r <= heap_size - 1 && a[r] > a[largest])
{
largest = r;
}

if (largest != i)
{
int k = a[i];
a[i] = a[largest];
a[largest] = k;
max_heapify(a, heap_size, largest);
}
}

void build_max_heap(int a[], int length, int& heap_size)
{
heap_size = length;
for (int i = length / 2 - 1; i >= 0; --i)
{
max_heapify(a, heap_size, i);
}
}

void heap_sort(int a[], int length)
{
int heap_size = 0;
build_max_heap(a, length, heap_size);

for (int i = length - 1; i >= 1; --i)
{
int k = a[0];
a[0] = a[i];
a[i] = k;

--heap_size;
max_heapify(a, heap_size, 0);
}
}

int partition(int a[], int p, int r)
{
int x = a[r];
int i = p - 1;
for (int j = p; j <= r - 1; ++j)
{
if (a[j] <= x)
{
++i;
int k = a[i];
a[i] = a[j];
a[j] = k;
}
}

int k = a[i + 1];
a[i + 1] = a[r];
a[r] = k;

return i + 1;
}

void quick_sort(int a[], int p, int r)
{
if (p < r)
{
int q = partition(a, p, r);
quick_sort(a, p, q - 1);
quick_sort(a, q + 1, r);
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120