Difference between revisions of "Sorting Arrays"

From CompSciWiki
Jump to: navigation, search
m (Edited Introduction. Note: Time Complexity is a second year concept. Might be too complicated for audience?)
 
(22 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[More With Arrays]] > [[Sorting Arrays]]
+
{{Template:1010Topic
 +
|Chapter_TOC=[[More With Arrays]] > [[Sorting Arrays]]
 +
|Previous=[[Searching Arrays]]
 +
|Next=[[Parallel Arrays]]
 
|Body=
 
|Body=
  
|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.
+
==Introduction==
 
+
In the previous section we learned how to search an array, but many searching algorithms have a requirement that the array is sorted. This chapter will cover algorithms that sort arrays.  There are a number of sorting algorithms, but we will only cover the most basic ones; they are Selection sort and bubble sort.
|Overview=}}
+
  
 
==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 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.
 
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.
<br/>
 
  
<h5> Pseudo code </h5>
+
 
<pre>
+
 
 +
<h5>Pseudo code:</h5>
 +
 
 +
 
 +
{{CodeBlock
 +
|Code=
 +
 
 +
 
 
procedure bubbleSort( A : list of sortable items )
 
procedure bubbleSort( A : list of sortable items )
 
   repeat
 
   repeat
Line 24: Line 33:
 
   until not swapped
 
   until not swapped
 
end procedure
 
end procedure
</pre>
 
<br/>
 
Let's look on an example: <br/>
 
Lets sort the following array |30|10|20|40|60|
 
  
When bubble sort algorithm will start it will compare the first two elements |30|10| it will swap them since 30 larger then 10.
 
<br/>
 
  
Now array will look as follows:|10|30|20|40|60|05|
+
}}
<br/>
+
  
Next the algorithm will compare 2nd and 3rd element (|30|20|), since 30 is larger than 20 the algorithm will swap them.
 
<br/>
 
Now array will look as follows: |10|20|30|40|60|05|
 
<br/>
 
  
Next 3rd and 4th element will be compared  (|30|40|) since 30 less than 40 , no swapping will be made. Now array will look as follows:|10|20|30|40|60|05|
 
<br/>
 
  
 +
Let's look at an example.Lets sort the following array:
  
Now 4th  element will be compared with 5th (|40|60|) since 40 is less than 60 no swapping will take place.
+
{{CodeBlock
<br/>
+
|Code=
Now array will look as follows: |10|20|30|40|60|05|
+
  
 +
{{!}}30{{!}}10{{!}}20{{!}}40{{!}}60{{!}}05{{!}}
  
Next 5th and 6th element will be compared (|60|05|) since 60 is grater then 05 swap the elements and new array will look as follows: |10|20|30|40|05|60|
+
}}
  
With each pass the element |05| will move to the front until no more swapping will take place. In that case the array is sorted<br/>
 
  
 +
When the bubble sort algorithm begins, it will compare the first two elements 30 and 10. Since 30 larger then 10, the algorithm will swap them.
 +
 +
 +
<h6>Current Array</h6>
 +
 +
{{OutputBlock
 +
|Code=
 +
 +
{{!}}10{{!}}30{{!}}20{{!}}40{{!}}60{{!}}05{{!}}
 +
 +
}}
 +
 +
Next, the algorithm will compare the 2nd and 3rd element 30 and 20. Since 30 is greater than 20, the algorithm will swap them.
 +
 +
<h6>Current Array:</h6>
 +
 +
{{OutputBlock
 +
|Code=
 +
 +
{{!}}10{{!}}20{{!}}30{{!}}40{{!}}60{{!}}05{{!}}
 +
 +
 +
}}
 +
 +
 +
Next, the algorithm will compare the 3rd and 4th elements, 30 and 40. Since 30 is less than 40 , the algorithm will not swap them.
 +
 +
 +
<h6>Current Array:</h6>
 +
 +
{{OutputBlock
 +
|Code=
 +
 +
{{!}}10{{!}}20{{!}}30{{!}}40{{!}}60{{!}}05{{!}}
 +
 +
}}
 +
 +
Next, the algorithm will compare the 4th and 5th elements, 40 and 60. Since 40 is less than 60 , the algorithm will not swap them.
 +
 +
<h6>Current Array:</h6>
 +
 +
{{OutputBlock
 +
|Code=
 +
 +
{{!}}10{{!}}20{{!}}30{{!}}40{{!}}60{{!}}05{{!}}
 +
 +
 +
}}
 +
 +
Next, the algorithm will compare the 5th and 6th elements, 60 and 05. Since 60 is greater than 05 , the algorithm will swap them.
 +
 +
<h6>Current Array:</h6>
 +
 +
{{OutputBlock
 +
|Code=
 +
 +
{{!}}10{{!}}20{{!}}30{{!}}40{{!}}05{{!}}60{{!}}
 +
 +
}}
 +
 +
 +
With each pass the element 05 will move to the front (because it is the smallest element in the array) all the elements are in the correct order. At this point the array is sorted.
 +
 +
 +
<h5>Complete code for Bubble sort:</h5>
 +
 +
 +
{{CodeBlock
 +
|Code=
  
<h5>Complete code for Bubble sort</h5>
 
<pre>
 
 
public static void bubbleSort(int[] array)
 
public static void bubbleSort(int[] array)
 
   {
 
   {
Line 87: Line 150:
 
   }
 
   }
  
</pre>
+
}}
  
The above is simple implementation of bubble sort, the above algorithm can be improved by shorting each pass. Since there is no necessity to check the last element since it is already in its place since the algorithm places the largest element at the end.
+
The above code is a simple implementation of the bubble sort. There are many algorithms which improve on this implementation. It is not necessary to check the last element since it is already in its place. This is because the algorithm places the largest element at the end.
  
  
Line 97: Line 160:
  
 
Example: sort this array
 
Example: sort this array
<pre>
+
 
|30|10|20|40|60|
+
 
</pre>
+
{{OutputBlock
 +
|Code=
 +
 
 +
{{!}}30{{!}}10{{!}}20{{!}}40{{!}}60{{!}}
 +
 
 +
}}
 +
 
 +
<h5>Pseudocode:</h5>
 +
 
 +
{{CodeBlock
 +
|Code=
  
 
1) Outer loop: iterate through each element
 
1) Outer loop: iterate through each element
<pre>
+
 
 
i = 0 (30)
 
i = 0 (30)
</pre>
+
 
  
 
2) Inner loop: iterate through the remaining elements to find a smaller element that should be in this position
 
2) Inner loop: iterate through the remaining elements to find a smaller element that should be in this position
<pre>
+
 
 
j = 1 (10)
 
j = 1 (10)
</pre>
+
 
  
 
3) Since the element at i is greater than the element at j, swap them - the array will now be:
 
3) Since the element at i is greater than the element at j, swap them - the array will now be:
<pre>
+
 
|10|30|20|40|60|
+
{{!}}10{{!}}30{{!}}20{{!}}40{{!}}60{{!}}
</pre>
+
 
  
 
4) Again with the inner loop, we will move to the next element and compare:
 
4) Again with the inner loop, we will move to the next element and compare:
<pre>
+
 
 
i = 0 (10), j = 2 (20)
 
i = 0 (10), j = 2 (20)
</pre>
+
 
  
 
Since all the other elements in the list are greater than the 0th (10), nothing else will happen for this outer loop.
 
Since all the other elements in the list are greater than the 0th (10), nothing else will happen for this outer loop.
  
 
Loop 2: In the outer loop, we will move to the next element (1) and loop through the remaining elements (starting at 2)
 
Loop 2: In the outer loop, we will move to the next element (1) and loop through the remaining elements (starting at 2)
<pre>
+
 
 
i = 1 (30), j = 2(20)
 
i = 1 (30), j = 2(20)
</pre>
+
 
 +
}}
  
 
Since the element at i is greater than the element at j, swap them and continue, giving us this array (which is now sorted!)
 
Since the element at i is greater than the element at j, swap them and continue, giving us this array (which is now sorted!)
<pre>
 
|10|20|30|40|60|
 
</pre>
 
  
Here is an example of a very simple selection sorting algorithm:
+
{{OutputBlock
 +
|Code=
 +
 
 +
{{!}}10{{!}}20{{!}}30{{!}}40{{!}}60{{!}}
 +
 
 +
}}
 +
 
 +
 
 +
Here is an example of a very simple implementation of a selection sort algorithm:
 +
 
 +
{{CodeBlock
 +
|Code=
  
<pre>
 
 
// Selection sort algorithm
 
// Selection sort algorithm
  
Line 150: Line 231:
 
     }
 
     }
 
}
 
}
</pre>
+
 
 +
}}
 +
 
 +
==Section Summary==
 +
 
 +
 
 +
In this section you learned how to sort arrays with two algorithms; Selection Sort and Bubble sort. As you know already there are many more sorting algorithms with different efficiency factors. From the examples above you saw how to sort array of integers, in the future same techniques can be applied to sort arrays with any kind of objects.
 +
 
 +
 
 +
}}

Latest revision as of 03:30, 8 December 2011

COMP 1010 Home > More With Arrays > Sorting Arrays


Introduction

In the previous section we learned how to search an array, but many searching algorithms have a requirement that the array is sorted. This chapter will cover algorithms that sort arrays. There are a number of sorting algorithms, but we will only cover the most basic ones; they 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 begins, it will compare the first two elements 30 and 10. Since 30 larger then 10, the algorithm will swap them.


Current Array
 |10|30|20|40|60|05| 

Next, the algorithm will compare the 2nd and 3rd element 30 and 20. Since 30 is greater than 20, the algorithm will swap them.

Current Array:
 |10|20|30|40|60|05| 


Next, the algorithm will compare the 3rd and 4th elements, 30 and 40. Since 30 is less than 40 , the algorithm will not swap them.


Current Array:
 |10|20|30|40|60|05| 

Next, the algorithm will compare the 4th and 5th elements, 40 and 60. Since 40 is less than 60 , the algorithm will not swap them.

Current Array:
 |10|20|30|40|60|05| 

Next, the algorithm will compare the 5th and 6th elements, 60 and 05. Since 60 is greater than 05 , the algorithm will swap them.

Current Array:
 |10|20|30|40|05|60| 


With each pass the element 05 will move to the front (because it is the smallest element in the array) all the elements are in the correct order. At this point the array is sorted.


Complete code for Bubble sort:


 public static void bubbleSort(int[] array)
   {
      int maxElement;  // Marks the last element to compare
      int index;       // Index of an element to compare
      int temp;        // Used to swap to elements
      
      // The outer loop positions maxElement at the last element
      // to compare during each pass through the array. Initially
      // maxElement is the index of the last element in the array.
      // During each iteration, it is decreased by one.
      for (maxElement = array.length - 1; maxElement >= 0; maxElement--)
      {
         // The inner loop steps through the array, comparing
         // each element with its neighbor. All of the elements
         // from index 0 thrugh maxElement are involved in the
         // comparison. If two elements are out of order, they
         // are swapped.
         for (index = 0; index <= maxElement - 1; index++)
         {
            // Compare an element with its neighbor.
            if (array[index] > array[index + 1])
            {
               // Swap the two elements.
               temp = array[index];
               array[index] = array[index + 1];
               array[index + 1] = temp;
            }
         }
      }
   } 

The above code is a simple implementation of the bubble sort. There are many algorithms which improve on this implementation. It is not necessary to check the last element since it is already in its place. This is because the algorithm places the largest element at the end.


Selection Sort

Selection sorts are used to sort the array into ascending (or descending) order. The idea behind a selection sort is very simple: iterate through each element in the array, and for each element, look at all remaining elements to see if there is something smaller that should be in this position. If there is, exchange the two values.

Example: sort this array


 |30|10|20|40|60| 
Pseudocode:
 1) Outer loop: iterate through each element

i = 0 (30)


2) Inner loop: iterate through the remaining elements to find a smaller element that should be in this position

j = 1 (10)


3) Since the element at i is greater than the element at j, swap them - the array will now be:

|10|30|20|40|60|


4) Again with the inner loop, we will move to the next element and compare:

i = 0 (10), j = 2 (20)


Since all the other elements in the list are greater than the 0th (10), nothing else will happen for this outer loop.

Loop 2: In the outer loop, we will move to the next element (1) and loop through the remaining elements (starting at 2)

i = 1 (30), j = 2(20) 

Since the element at i is greater than the element at j, swap them and continue, giving us this array (which is now sorted!)

 |10|20|30|40|60| 


Here is an example of a very simple implementation of a selection sort algorithm:

 // Selection sort algorithm

public static void selectionSort(int[] haystack) {
    for (int i = 0; i < haystack.length - 1; i++) {
        for (int j = i + 1; j < haystack.length; j++) {
            if (haystack[i] > haystack[j]) {
                //... Exchange elements
                int temp = haystack[i];
                haystack[i] = haystack[j];
                haystack[j] = temp;
            }
        }
    }
} 

Section Summary

In this section you learned how to sort arrays with two algorithms; Selection Sort and Bubble sort. As you know already there are many more sorting algorithms with different efficiency factors. From the examples above you saw how to sort array of integers, in the future same techniques can be applied to sort arrays with any kind of objects.

Previous Page: Searching Arrays Next Page: Parallel Arrays