There is a unordered array of all-in-one-to-N, sorted

Source: Internet
Author: User

title : there are,.. n an unordered array of integers for sorting algorithms. Requires time complexity O (n), Spatial complexity O (1).

Analysis : The ordering of general arrays is obviously not possible with O (n). Since the title is so demanding, it is certain that the original array has a certain regularity, allowing people to look for an opportunity.

For example: The original array: a = [10, 6, 9, 5, 2, 8,4,7,1,3], if you sort them from small to large and should be B = [1,2,3,4,5,6,7,8,9,10], that is, if we observe a-to-B mapping relationship is: A[i] The position in B is a[i]-1, or a[i]=b[a[i]-1]

Code:

#include <iostream>#include<ctime>using namespacestd;voidPrintintBintN) {     for(inti =0; I < n; i++) {cout<< A[i] <<","; } cout<<Endl;}
voidFancysort (intBintN) { inttemp; intSwapcount =0; for(inti =0; I <N;) {Swapcount++; //The position of A[i]-1 as A[i] in an ordered array//therefore, A[i] is in the right place after the exchange of A[i] and A[a[i]-1]//but the exchange of a[a[i]-1] is not necessarily in the right placetemp = A[a[i]-1]; A[a[i]-1] =A[i]; A[i]=temp; cout<<"Section"<< Swapcount <<"Secondary Exchange"<<"i="<< I <<Endl; Print (A, n); //until I have the correct number, we begin to deal with the next if(A[i] = = i +1) I++; }}intMain () { while(true) {cout<<"Enter N:"<<Endl; intN; CIN>>N; int* A =New int[n]; for(inti =0; I < n; i++) {A[i]=0; } //Array (,.... Up to n unordered array) gives initialization random valueSrand (Time (0)); for(inti =1; I <=N;) {intRANDV = rand ()%N; if(A[RANDV] = =0) {A[RANDV]=i; I++; }} cout<<"The input array:"; Print (A, n); Fancysort (A, n); cout<<"Sort Result:"; Print (A, n); cout<<Endl; } return 0;}

Results:

There is a unordered array of all-in-one-to-N, sorted

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.