Skip to content

Commit 44ef3ea

Browse files
authored
Add files via upload
1 parent cdde17f commit 44ef3ea

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

Diff for: Sorting Technique/01 Bubble Sort.c

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
void swap(int* x, int* y) // function for swapping
5+
{
6+
int temp = *x;
7+
*x = *y;
8+
*y = temp;
9+
}
10+
11+
void Bubble(int A[], int n) // size of array // no of elements
12+
{
13+
int i, j, flag = 0; // flag is for adptive (Criteria)
14+
for (i = 0; i < n - 1; i++)
15+
{
16+
flag = 0;
17+
for (j = 0; j < n - i - 1; j++)
18+
{
19+
if (A[j] > A[j + 1])
20+
{
21+
swap(&A[j], &A[j + 1]); // if is greater then swap the elements
22+
flag = 1;
23+
}
24+
}
25+
if (flag == 0)
26+
break;
27+
28+
}
29+
}
30+
int main()
31+
{
32+
int A[20], i;
33+
int n = sizeof(A) / sizeof(int);
34+
scanf_s("%d", &n);
35+
for (i = 0; i < n; i++)
36+
{
37+
scanf_s("%d", & A[i]);
38+
}
39+
40+
Bubble(A, n); // callig the funtion
41+
42+
for (i = 0; i < n; i++)
43+
printf("%d ", A[i]);
44+
printf("\n");
45+
46+
return 0;
47+
}
48+
49+
// Bubble sort is Adptive: if the list is sorted it will use flag // Bubble sort is stable : in case of duplicate
50+
// time complexity is : min = o(n) - in the case of Adaptivity
51+
// : max = o(n2)

Diff for: Sorting Technique/02 BubbleSort.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
template <class T>
6+
void Print(T& vec, int n, string s){
7+
cout << s << ": [" << flush;
8+
for (int i=0; i<n; i++){
9+
cout << vec[i] << flush;
10+
if (i < n-1){
11+
cout << ", " << flush;
12+
}
13+
}
14+
cout << "]" << endl;
15+
}
16+
17+
void swap(int* x, int* y){
18+
int temp = *x;
19+
*x = *y;
20+
*y = temp;
21+
}
22+
23+
void BubbleSort(int A[], int n){
24+
int flag = 0;
25+
for (int i=0; i<n-1; i++){
26+
for (int j=0; j<n-1-i; j++){
27+
if (A[j] > A[j+1]){
28+
swap(&A[j], &A[j+1]);
29+
flag = 1;
30+
}
31+
}
32+
if (flag == 0){
33+
return;
34+
}
35+
}
36+
}
37+
38+
int main() {
39+
40+
int A[] = {3, 7, 9, 10, 6, 5, 12, 4, 11, 2};
41+
int n = sizeof(A)/sizeof(A[0]);
42+
Print(A, n, "\t\tA");
43+
44+
BubbleSort(A, n);
45+
Print(A, n, " Sorted A");
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)