Program 9
Program 9
OBJECTIVE
THEORY
Sorting is arrangement/storage of data in the sorted order which can be ascending or descending.
Any sort algorithm that uses main memory exclusively during the sorting is known internal
sorting.
Bubble sort is a simple sorting technique which uses comparision based algorithm in which each
pair of adjacent elements are compared and are swapped if not in correct order. This technique is
not suitable for large data sets.
Selection is the simplest sorting algorithm which first finds the smallest element in the array and
swaps it with the first element of the array, and then finds the second smallest element in the
array and exchanges it with the element on the second position.
Insertion sort is not much efficient on large data than more advanced approaches like quick sort,
heap sort, or merge sort. In this technique we start by making the element at the index 1 as key.
We compare the key with the elements before it. If the key element is less than the first element,
we place it before the first element else if it is greater than the first element we place it after the
first element. We keep on repeating the process till the array is sorted.
PSEUDO CODE
BEGIN:
Temp=*xp
*xp=*yp
*yp=temp
END;
ALGORITHM BubbleSort(arr, n)
BEGIN:
END;
ALGORITHM SelectionSort(arr, n)
BEGIN:
min_idx=0
min_idx = i
min_idx = j
swap(&arr[min_idx], &arr[i])
END;
ALGORITHM InsertionSort(arr, n)
BEGIN:
key=0
FOR i = 1 TO i < n DO
key = arr[i]
j=i-1
WHILE j >= 0 AND arr[j] > key DO
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = key
END;
SOURCE CODE
#include <stdio.h>
*xp = *yp;
*yp = temp;
swap(&arr[j], &arr[j+1]);
int i, j, min_idx;
min_idx = i;
min_idx = j;
swap(&arr[min_idx], &arr[i]);
int i, key, j;
key = arr[i];
j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
int main() {
int n, choice;
scanf("%d", &n);
int arr[n];
for(int i=0;i<n;i++){
scanf("%d", &arr[i]);
printf("Enter 1 for bubble sort, 2 for selection sort, and 3 for insertion sort");
scanf("%d",&choice);
switch (choice)
case 1:
BubbleSort(arr, n);
break;
case 2:
SelectionSort(arr, n);
break;
case 3:
InsertionSort(arr, n);
break;
default:
printf("Invalid Choice");
break;
return 0;
OUTPUT
Enter 1 for bubble sort, 2 for selection sort, and 3 for insertion sort1