-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubblesort_insertionsort_selectionsort.c
116 lines (106 loc) · 2.17 KB
/
bubblesort_insertionsort_selectionsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#define SIZE 10
int i, j, n, temp, a[SIZE];
void entry()
{
printf("\nEnter no. of elements in the array: ");
scanf("%d", &n);
printf("\nEnter the elements: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
}
void display()
{
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
}
void bubble_sort()
{
int temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("Sorted array after bubble sort: ");
display();
}
void insertion_sort()
{
for (i = 1; i < n; i++)
{
temp = a[i];
j = i - 1;
while ((temp < a[j]) && (j >= 0))
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
printf("Sorted array after insertion sort: ");
display(a);
}
int smallest(int k)
{
int pos = k, small = a[k], i;
for (i = k + 1; i < n; i++)
{
if (a[i] < small)
{
small = a[i];
pos = i;
}
}
return pos;
}
void selection_sort()
{
int k, pos;
for (k = 0; k < n; k++)
{
pos = smallest(k);
temp = a[k];
a[k] = a[pos];
a[pos] = temp;
}
printf("Sorted array after selection sort: ");
display();
}
void main()
{
int ch;
do
{
printf("\n\t\t\tMENU\n");
printf("1. Entry\t\t2. Display\t\t3. Bubble Sort\n4. Insertion Sort\t5. Selection Sort\t6. Exit\n");
printf("Enter choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
entry();
break;
case 2:
printf("Array:\t");
display();
break;
case 3:
bubble_sort();
break;
case 4:
insertion_sort();
break;
case 5:
selection_sort();
break;
}
} while (ch >= 1 && ch <= 5);
}