Simple Sorting Algorithms
Simple Sorting Algorithms
The element with the lowest value is selected and exchanged with the
element in the first position. Then, the smallest value among the
second position.
List[i] are continued until all elements are in their proper positions
Selection Sort
Basic Idea:
Basic Idea:
Loop through array from i=0 to n and swap adjacent elements if they are
out of order.
Implementation:
void bubble_sort(list[])
{ Analysis of Bubble Sort
int i,j,temp;
How many comparisons?
for(i=0;i<n; i++){
(n-1)+(n-2)+…+1= O(n2)
for(j=n-1;j>i; j--){
How many swaps?
if(list[j]<list[j-1]){
(n-1)+(n-2)+…+1= O(n2)
temp=list[j];
Space?
list[j]=list[j-1];
In-place algorithm.
list[j-1]=temp;
}//swap adjacent elements
}//end of inner loop
}//end of outer loop
}//end of bubble_sort