Why selection sort is unstable




















Different zipping conventions either require the ranges to be of the same length crashing or throwing otherwise or fill in the empty data should one of the ranges be too short.

While seemingly obvious in such a simple program, be careful in real-world code. Why Selection sort can be stable or unstable. Asked 3 Months ago Answers: 5 Viewed 17 times. Well, selection sort works by finding the 'least' value in a set of values, then swap it with the first value : Code: 2, 3, 1, 1 scan 0 to n and find 'least' value 1, 3, 2, 1 swap 'least' with element 0. To make this stable, instead of swaping values, insert the 'least' value instead : Code: 2, 3, 1, 1 scan 0 to n and find 'least' value 1, 2, 3, 1 insert 'least' at pos 0, pushing other elements back.

QuadPart - start. Alexander Trauzzi. Only authorized users can answer the question. Please sign in first, or register a free account. Input : 4 A 5 3 2 4 B 1 Output : 1 2 3 4 B 4 A 5 Stable Selection Sort would have produced Output : 1 2 3 4 A 4 B 5 Selection sort works by finding the minimum element and then inserting it in its correct position by swapping with the element which is in the position of this minimum element.

This is what makes it unstable. In the above example 4 A was pushed after 4 B and after complete sorting this 4 A remains after this 4 B. Hence resulting in unstability. Selection sort can be made Stable if instead of swapping, the minimum element is placed in its position without swapping i.

In simple terms use a technique like insertion sort which means inserting element in its correct place. Example: 4 A 5 3 2 4B 1 First minimum element is 1, now instead of swapping. Insert 1 in its correct place and pushing every element one step forward i. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.

See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Skip to content. Change Language. As a result, sorted elements in ascending order are- 2, 5, 6, 7, 11 Selection Sort Algorithm- Let A be an array with n elements. The state of array after the loops are finished is as shown- With each loop cycle, The minimum element in unsorted sub-array is selected.

It is then placed at the correct location in the sorted sub-array until array A is completely sorted. Time Complexity Analysis- Selection sort algorithm consists of two nested loops. Owing to the two nested loops, it has O n 2 time complexity. It performs all computation in the original array and no other array is used. Hence, the space complexity works out to be O 1.

Important Notes- Selection sort is not a very efficient algorithm when data sets are large.



0コメント

  • 1000 / 1000