Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Sorting a range of numbers - In place

I'm trying to solve the following question :

We are given an array containing ‘n’ objects. Each object, when created, was assigned a unique number from 1 to ‘n’ based on their creation sequence. This means that the object with sequence number ‘3’ was created just before the object with sequence number ‘4’.

Write a function to sort the objects in-place on their creation sequence number in O(n)O(n) and without any extra space. For simplicity, let’s assume we are passed an integer array containing only the sequence numbers, though each number is actually an object.

Eg : Input : [2, 6, 4, 3, 1, 5] Output : [1, 2, 3, 4, 5, 6]

My approach :

void sortInPlace(int *arr,int n){

    for(int i=0;i<n;i++){

        if(arr[i] != arr[arr[i]-1]){
            swap(arr[i],arr[arr[i]-1]);
        }
    }


}

int main(){

    int n;
    cout<<"
 Enter number of elements:";
    cin>>n;

    int arr[n];
    cout<<"
 Enter the elements :";
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }

    sortInPlace(arr,n);

    cout<<"
 Sorted Array :";
    for(int i = 0; i < n ; i++){

        cout<<arr[i];
    }

}


But, this doesn't produce the right results.

Actual solution :

enter image description here

The only difference I could find is the While loop that they have used.

The while loop in the solution has an extra iteration to increment the 'i' , whereas , My solution does it in a for loop without requiring additional iterations.

Example : My approach


Input : [1,5,6,4,3,2]
Output : [1,3,2,4,5,6]
Expected output : [1,2,3,4,5,6]

But, why doesn't it work ? Could someone please tell me if I am missing something ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On every iteration of for (int i=0; i < n; i++), i is incremented.

The while loop only increments i if no swap was made.

To get the same behaviour, the for version must not increment i when a swap is made.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...