Sorting Arrays

From CompSciWiki
Revision as of 14:49, 6 December 2011 by VitaliU (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > More With Arrays > Sorting Arrays


Introduction

In the previous section we learned how to search an array, but there is a requirement that the array will be sorted. In this chapter we are going to cover sorting algorithms to sort arrays, although there are number of sorting algorithms with different" time complexity ", the most common ones are Selection sort and bubble sort.


Bubble Sort

Bubble sort is an easy algorithm to master when learning sorting arrays. This algorithm called bubble sort since it takes the larger elements "bubbles" and put them at the end of the array with each pass. Bubble sort compares each time two elements and if they are not in order swapping them.Next the algorithm compares next set of elements, this process continues until there is no more items to swap.


Pseudo code:


 procedure bubbleSort( A : list of sortable items )
  repeat
    swapped = false
    for i = 1 to length(A) - 1 inclusive do:
      if A[i-1] > A[i] then
        swap( A[i-1], A[i] )
        swapped = true
      end if
    end for
  until not swapped
end procedure 


Let's look at an example.Lets sort the following array:

 |30|10|20|40|60|05| 


When the bubble sort algorithm starts, it will compare the first two elements

   

Previous Page: Sorting Arrays Next Page: More With Arrays Review Questions and Exercises