2 WAP to sort list of elements and give user op ons to choose inser on,bubble and
selec on sort
1 #include <stdio.h>
2 #include <stdlib.h>
3 void insertionSort(int a[], int n) {
4 for (int i = 1; i < n; i++) {
5 int key = a[i], j = i - 1;
6 while (j >= 0 && a[j] > key)
7 a[j + 1] = a[j--];
8 a[j + 1] = key;
9 }
10 }
11
12 void bubbleSort(int a[], int n) {
13 for (int i = 0; i < n - 1; i++)
14 for (int j = 0; j < n - i - 1; j++)
15 if (a[j] > a[j + 1]) {
16 int t = a[j];
17 a[j] = a[j + 1];
18 a[j + 1] = t;
19 }
20 }
21
22 void selectionSort(int a[], int n) {
23 for (int i = 0; i < n - 1; i++) {
24 int min = i;
25 for (int j = i + 1; j < n; j++)
26 if (a[j] < a[min]) min = j;
27 int t = a[i];
28 a[i] = a[min];
29 a[min] = t;
30 }
31 }
32
33 void printArray(int a[], int n) {
34 for (int i = 0; i < n; i++)
35 printf("%d ", a[i]);
36 printf("\n");
37 }
38
39 int main() {
40 int a[50], n, choice;
41
42 printf("\n1. Insertion Sort\n2. Bubble Sort\n3. Selection Sort ");
43 scanf("%d", &choice);
44 printf("Enter number of elements: ");
45 scanf("%d", &n);
46 printf("Enter %d elements:\n", n);
47 for (int i = 0; i < n; i++)
48 scanf("%d", &a[i]);
49 if (choice == 1)
50 insertionSort(a, n);
51 else if (choice == 2)
52 bubbleSort(a, n);
53 else if (choice == 3)
54 selectionSort(a, n);
55 else {
56 printf("Invalid choice\n");
57 return 1;
58 }
59
60 printf("Sorted array:\n");
61 printArray(a, n);
62 system("pause");
63 return 0;
64 }
65
OUPUT
1. Inser on Sort
2. Bubble Sort
3. Selec on Sort 1
Enter number of elements: 8
Enter 8 elements:
38295810
Sorted array:
01235889