Sorting is an important technique which every programmer should know. Here is my part to explain you the three basic sorting methodologies.For any queries kindly comment in the comment section.
2. INTRODUCTION
๏ง Sorting refers to arranging a set of data in a logical order.
๏ง Arrangement of the data in ascending or descending order.
๏ง Sorting is among most basic problem in algorithm design.
๏ง Can be done on names, numbers and records
๏ง Example: Telephone Directory ,Dictionary.
๏ง Being unique, phone number can work as a key to locate any record in the list.
4. The two main criterias to judge which
algorithm is better than the other have
been:
1)Time taken to sort the given data.
2)Memory Space required to do so.
SORTING EFFICIENCY
6. Done by comparing two
adjacent elements.
Simplest technique.
For n elements, n-1 pass
required.
BUBBLE SORTING
7.
8.
9. Conceptually simplest algo.
Finds smallest no and swaps with
element at first position.
Repeatedly selects the next smallest
no and swaps it into right place hence
the name.
SELECTION SORT
10.
11. #include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of uns/* Function to print an array */
orted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
12. Efficient for smaller data.
Better than selection and bubble sort.
Space complexity less.
Stable sorting technique.
INSERTION SORT
13.
14. void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}