Data structure insert sort of pit and thought correction

Source: Internet
Author: User

There is a set of data 8 2 3 1 10 9 6

Thinking of inserting sort:

First, compare the second number to the first: if the latter is smaller

Swapping 8 and 2

Results: 2 8 3 1 10 9 6


After looking at 3:3 less than 8 so the exchange then 3:2 large in accordance with the correct order is not exchanged

Results 2 3 8 1 10 9 6


See after 1 1:8 small switching ratio 3 small switching than 2 small switching

Results 1 2 3 8 10 9 6


etc...


Error code:

Template<typename t>
void insertselection (t* arr, int N) {for
	
	(int i = 1; i < N; ++i) {
		T key = arr[ I];
		Int J;
	    
		for (j = i-1; J > 0 && arr[j] < key; j--) {
			arr[j] = arr[j-1];
		}

		
		   ARR[J] = key;
	}
}


Code Understanding:

Select a value to compare for insertion

T key = Arr[i];


ARR[J+1] = Arr[j] used to move

Why not swap with swap? Because key is going to be inserted

Why Arr[j + 1] = Arr[j] instead of arr[j] = arr[j-1]

Because it is compared with the following value and key:


Correct code:

void Insertselectiontwo (int* arr, int N) {for
	
	(int i = 1; i<n; ++i) {

		int temp = arr[i];
		int j = i-1;    Parameters for comparison
		
		while (J > 0 && arr[j] > Temp) {
			arr[j + 1] = Arr[j];      To empty a value to insert the key to be inserted so that the value is overwritten 		
	                j--;
		}
	    
		ARR[J+1] = temp//Because the overlay above will now have two more identical values this is the insertion point value is inserted
	}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.