Sorting algorithm (selective sorting and heap sorting) C language implementation
Select sort
/The number of comparisons required in the selection and sorting process has nothing to do with the arrangement of the record sequence to be sorted in the initial state. When i=1, n-1 comparisons are required; when i=2, n-2 comparisons are required; and so on, the total number of comparisons required is (n-1)+(n-2)+ …+2+1=n(n-1)/2, that is, the time complexity of the comparison operation is O(n^2), and the time complexity of the move operation is O(n). Space complexity O(1)
#include<stdio.h>
void SelectSort(int a[],int n){
int i;
int temp;
for(i=0;i<n-1;i++){
//一共进行 n-1次
int min=i; //记录最小元素位置
int j;
for(j=i+1;j<n;j++) //在a【1 n-1】中选择最小
if(a[j]<a[min])min=j; //更新最小元素位置
if(min!=i){
//进行交换
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
}
void Printarr(int a[],int n) //输出数组
{
int i;
for(i=0;i<n;i++){
printf("%d",a[i]);
}
return;
}
int main(){
//主函数
int a[]={
1,8,7,5,6};
int n=5;
printf("未排序的数\n");
Printarr(a,n);
printf("\n");
SelectSort(a,n);
printf("冒泡排好序的数\n");
Printarr(a,n);
return 0;
}
result
Heap Sort (HEAP)
Heap sorting is a further improvement of tree selection sorting. The logic of the file to be sorted is regarded as a complete binary tree and the concept of heap is used
{90 70 80 60 10 40 50 30 20} The i-th number is greater than the 2i and 2i+1 numbers (large root pile or large top pile);
{10 20 70 30 50 90 80 60 40} The i-th number is smaller than the 2i and 2i+1 numbers (small root pile or small top pile);
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void max_heapify(int arr[], int start, int end)
{
//建立父节点指标和子节点指标
int dad = start;
int son = dad * 2 + 1;
while (son <= end) //若子节点指标在范围内才做比较
{
if (son + 1 <= end && arr[son] < arr[son + 1])
//先比较两个子节点大小,选择最大的
son++;
if (arr[dad] > arr[son]) //如果父节点大於子节点代表调整完毕,直接跳出函数
return;
else //否则交换父子内容再继续子节点和孙节点比较
{
swap(&arr[dad], &arr[son]);
dad = son;
son = dad * 2 + 1;
}
}
}
void heap_sort(int arr[], int n)
{
int i;
//初始化,i从最後一个父节点开始调整
for (i = n / 2 - 1; i >= 0; i--)
max_heapify(arr, i, n - 1);
//先将第一个元素和已排好元素前一位做交换,再重新调整,直到排序完毕
for (i = n - 1; i > 0; i--)
{
swap(&arr[0], &arr[i]);
max_heapify(arr, 0, i - 1);
}
}
int main() {
int arr[] = {
1,55,87,84,56,45,6,14,64,65,57,65};
int n=12;
heap_sort(arr, n);
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
result