sorting2 - Sorting - 2 Insertion sort Selection sort Bubble...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Sorting - 2 Insertion sort Selection sort Bubble sort Selection Sort Selection sort is an attempt to localize the exchanges of array elements by finding a misplaced element first and putting it in its final place. The list is divided into two sublists, sorted and unsorted , which are divided by an imaginary wall. We select the smallest element from the unsorted sublist and swap it with the element at the beginning of the unsorted data. Then the smallest value among the remaining elements is selected and put in the second position and so on. After each selection and swapping, the imaginary wall between the two sublists move one element ahead, increasing the number of sorted elements and decreasing the number of unsorted ones. Each time we move one element from the unsorted sublist to the sorted sublist, we say that we have completed a sort pass. A list of n elements requires n-1 passes to completely rearrange the data. Selection Sort Example Sorted Unsorted 23 78 45 8 32 56 8 78 45 23 32 56 8 23 45 78 32 56 8 23 32 78 45 56 8 23 32 45 78 56 8 23 32 45 56 78 Original List After pass 1 After pass 2 After pass 3 After pass 4 After pass 5 Selection Sort Algorithm /* Sorts by selecting smallest element in unsorted portion of array and exchanging it with element at the beginning of the unsorted list. */ void selectionSort(int list, int n) { int cur, j, smallest, tempData; for (cur = 0; cur <= n; cur ++){ smallest = cur; for ( j = cur +1; j <= n ; j++) if(list[ j ] < list[smallest]) smallest = j ; // Smallest selected; swap with current element tempData = list[cur]; list[cur] = list[smallest]; list[smallest] = tempData; } } The outer loop is executed n times, and the inner loop iterates j = (n 1 cur) times....
View Full Document

Page1 / 10

sorting2 - Sorting - 2 Insertion sort Selection sort Bubble...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online