Chapter 2 - Elementary Searching and Sorting Algorithms
Chapter 2 - Elementary Searching and Sorting Algorithms
List index 0 1 2 3 4 5 6 7
Data C A E F N Q R K
Key=Q after six comparison the algorithm returns found
Key=X after 8 comparison the algorithm returns found false
If any of these other is less than the current first element
then the first element is swapped with that element.
The above step is repeated with the second, third and all
other subsequent elements.
Implementation:
void swap( dataType x, dataType y)
{
dataType temp;
temp=x;
x=y;
y=temp;
}
for (i=0;i<=n-2;i++)
for(j=i+1;j<=n-1;j++)
if(dataElement[i]>dataElement[j])
Swap(dataElement[i],dtataElement[j]);
Example
Implementation:
for (int i = 0; i < n-1; i++)
for (int j = n-1; j > i; --j)
if (data[j] < data[j-1])
swap(data[j],data[j-1]);
Example data element= 5,2,3,8,1
Analysis
Passes number of comparison number of swaps
1 n-1 n-1
2 n-2 n-2
. . .
. . .
. . .
n-1 1 1
total n(n-1)/2 n(n-1)/2
=O(n2)
Selection Sort Algorithm
It is in many ways similar to both simple and bubble
algorithm.
Rather than swapping the neighbors continuously as the
algorithm traverses the sub array to be sorted, as done in
the bubble sort case, this algorithm finds the minimum
element of the sub array and swaps it with the pivot
elements.
Implementation
Deadline: 05/04/2023