[C++] Principle and Implementation of Bubble Sort and Selection Sort

[C++] Bubble sort and selection sort

 

1. Bubble sort

      Bubble sort is a stable sorting algorithm with a time complexity of O(n).

principle:

                

        The bubble sort algorithm works as follows: (from back to front)

(1) Compare adjacent elements. If the first is bigger than the second, swap the two of them.

(2) Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.

(3) Repeat the above steps for all elements except the last one.

(4) Continue to repeat the above steps for fewer and fewer elements each time, until there are no pairs of numbers to compare.

Code:

for(int i=1;i<10;i++)
	{
	for(int j=0;j<10-i;j++)
	{
		if(b[j]>b[j+1])
		{
			int temp=b[j];
			b[j]=b[j+1];
			b[j+1]=temp;
		}
	}

 

operation result:

The input is: 10 9 8 7 6 5 4 3 2 1 

                        

2 . selection sort

      Selection sort ( Selectionsort ) is an unstable sorting method. Each time, the smallest (or largest) element is selected from the data elements to be sorted , and the order is placed at the end of the sorted sequence until all the data elements are to be sorted. Sorted data elements are exhausted.

      Why is he unstable?

      In a selection, if an element is smaller than the current element, and the smaller element appears after an element equal to the current element, then the post-swap stability is broken. For example, the sequence 5 8 5 2 9 , we know that the first selection of the first element 5 will be exchanged with 2 , then the relative order of the two 5s in the original sequence will be destroyed, so the selection sort is not A stable sorting algorithm.

principle:

The first pass selects the element with the smallest/largest keyword from the data sequence of n elements and puts it in the front/rear position, and the next pass selects the smallest/largest element from the n-1 elements and puts it in the front/rear position. rear position. And so on, after n-1 times to complete the sorting.

Code:

for(int i=0;i<9;i++)
	{
		int min = i;
	for(int j=i+1;j<10;j++)
	{
		if(c[j]<c[min]) //find the subscript of the minimum value
		{
			min = j;
		}
	}
	if(min!=i){
		int temp=c[i];
		c [i] = c [min];
		c[min]=temp;
	}

operation result:

The input is: 10 9 8 7 6 5 4 3 2 1 

                        

 -------------------------------------------         END      -------------------------------------

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818011&siteId=291194637
Recommended