C language --- selection sort and heap sort


foreword

Heap sorting is a kind of selection sorting. Today we will explain itheap sortandsimple selection sort


1. Simple selection sort

1 Introduction

Selection sort is a simple and intuitive sorting algorithm. Its working principle is to select the smallest (or largest) element from the data elements to be sorted each time, and store it at the beginning of the sequence until all the data elements to be sorted are exhausted.
Time complexity: O(n²) Stability: unstable

2. Algorithm idea

Dynamically display the graph to fully understand the selection sort
insert image description here
From the graph we can see:

  1. first trip atunsorted sequenceFind the minimum value and place it at the beginning of the sequence
  2. In the second pass, start looking for the minimum value from the back of the arranged elements, and then put it at the front
  3. Search in turn, sort... until all elements are arranged in order.

3. Code implementation

Simple selection sort:

void select_sort(int *p,int n)\n
{
    
     
 int i,j;
    int min = 0;
    for(i = 0;i < n - 1;i++)//排序次数
    {
    
    
        min = i;
        for(j = i + 1;j < n;j++)
        {
    
    
            if(p[j] < p[min])
            {
    
    
                min = j;//记录交换的元素下标值
            }
        }
        if(i != min)
        {
    
    
            int temp = p[i];
            p[i] = p[min];
            p[min] = temp;
        }  
int main()
{
    
    
	int arr[num] = {
    
     3,1,4,5,2,7,9,0,8,6 };
	select_sort(arr, num);
	for (int i = 0; i < num; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
}

Then think about it, can it be improved? For example, we find the maximum and minimum values ​​at the same time, and then put the minimum value at the front of the sequence and the maximum value at the end of the sequence.
Code:

void swap(int* q, int* a)
{
    
    
	int tem = *q;
	*q = *a;
	*a = tem;
}
void select_sort(int* a, int n)
{
    
    
	int begin = 0, end = n - 1;
	while (begin < end)
	{
    
    	
		int min = begin, max = begin;
		for (int i = min; i < end; i++)
		{
    
    
			if (a[i] < a[min])
				min = i;
			if (a[i] > a[max])
				max = i;
		}
		swap(&a[min], &a[begin]);
		// begin == maxi时,最大被换走了,修正一下maxi的位置
		if (begin == max)
			max = min;
		swap(&a[max], &a[end]);
		begin++; end--;
	}
}
int main()
{
    
    
	int arr[num] = {
    
     3,1,4,5,2,7,9,0,8,6 };
	select_sort(arr, num);
	for (int i = 0; i < num; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
}

Be careful when using this codeWhen the begin position is at the subscript of max, after min and begin are interchanged, the subscript value of max has been replaced, and the maximum value is at the subscript value of min , so it needs to be judged.
operation result:
insert image description here

2. Heap sort

1 Introduction

Heapsort (English: Heapsort) refers to a sorting algorithm designed using the data structure of the heap. A heap is a structure that approximates a complete binary tree, and at the same time satisfies the nature of accumulation: that is, the key value or index of a child node is always smaller (or larger) than its parent node.
Time complexity: O(N*logN) Space complexity: O(1) Stability: Unstable
And if you wantTo use heap sorting, you need to build a heap first, and then choose big push or small heap sorting

2. Algorithm idea

  1. Construct the initial sequence of keywords to be sorted (R0, R1, R2...Rn) intobig top pile, this heap is the initial unordered area.
  2. Exchange the top element R[0] with the last element R[n], and get a new unordered area (R0, R1, R2,...Rn-1) and a new ordered area (Rn).
  3. Since the new heap top R[1] after the exchange may violate the nature of the heap, it is necessary to adjust the current unordered area (R0, R1, R2,...Rn-1) to a new heap, and then combine R[1] with none again The last element of the sequence area is exchanged to obtain a new disordered area (R0, R1, R2...Rn-2) and a new ordered area (Rn-1, Rn).
  4. Repeat this process until the number of elements in the ordered area is n-1, then the entire sorting process is complete

Heap Image Display and Explanation:
insert image description here
Dynamic display diagram of large heap construction:
insert image description here
watch patiently, we can see that it first becomes the top of the large heap (the top element of the heap is the largest, and the parent node is larger than the child node), and then the top element of the heap is exchanged with the last element , the last element becomes the top element of the heap, and then it is exchanged with the largest child node, and finally the second largest leaf node is exchanged to become the top element of the heap, and the original element needs to be adjusted to its suitable position .

Red is the ordered range that has been sorted, yellow is the exchange of the top element and the end element of the heap, and green is the range to be sorted

Note: The focus is on building heaps (large and small heaps)

3. Code implementation

code show as below:

void Swap(int* px, int* py)
{
    
    
	int tmp = *px;
	*px = *py;
	*py = tmp;
}
void AdjustDown(int* a, int n, int parent)
{
    
    
	int child = parent * 2 + 1;
	while (child < n)
	{
    
    
		// 选出左右孩子中小的那一个
		if (child + 1 < n && a[child + 1] > a[child])
		{
    
    
			++child;
		}

		// 如果小的孩子小于父亲,则交换,并继续向下调整
		if (a[child] > a[parent])
		{
    
    
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
    
    
			break;
		}
	}
}

// 堆排序
void HeapSort(int* a, int n)
{
    
    
	// O(N)
	for (int i = (n - 1 - 1) / 2; i >= 0; --i)
	{
    
    
		AdjustDown(a, n, i);
	}

	// O(N*logN)
	int end = n - 1;
	while (end > 0)
	{
    
    
		Swap(&a[0], &a[end]);
		AdjustDown(a, end, 0);
		--end;
	}
}
int main()
{
    
    
	int arr[num] = {
    
     3,1,4,5,2,7,9,0,8,6 };
	HeapSort(arr, num);
	for (int i = 0; i < num; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
}

operation result:
insert image description here


Summarize

Heap sorting is difficult to understand, it can be digested by drawing, and the focus is on building heaps.
The dynamic diagrams of the article are all the diagrams that the author found on the Internet and think they are the most suitable and easy to understand. The pictures in this article are all from Baidu

I think heap sorting is difficult to understand, and thousands of people need to draw pictures to understand it. All IT personnel who study hard, work hard together. I wish you all success in your studies and wealth.
---------Blessings from Cainiao TQ02

Guess you like

Origin blog.csdn.net/m0_74097410/article/details/128836558
Recommended