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