Skip to content

Commit 0893d9f

Browse files
authored
Add files via upload
1 parent b0420a3 commit 0893d9f

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Diff for: Sorting Technique/05 Selection Sort.c

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <stdio.h>
2+
3+
void swap(int* a, int* b)
4+
{
5+
int temp = *a;
6+
*a = *b;
7+
*b = temp;
8+
}
9+
void selectionsort(int A[], int n)
10+
{
11+
int i, j, k; // for indexes
12+
for (i = 0; i < n - 1; i++) // for passes // in 1st pass we will get the smallest element
13+
{
14+
for (j = k = i; j < n; j++) // for checing all elements // keep i,j,k on 1st pos and strating moving j everytime and compare with k
15+
{
16+
// move j to next element and comp with k . if j is smaller then k then bring k at j..
17+
if (A[j] < A[k]) // if j is less then k then move k and we will
18+
k = j; // now k is pointing on the smallest elements
19+
}
20+
swap(&A[i], &A[k]); // now swap k with i then we will get the smallest elements at that position (i) // in this only one swap will happen
21+
}
22+
}
23+
int main()
24+
{
25+
int no, i, A[20];
26+
no = sizeof(A) / sizeof(int);
27+
scanf_s("%d", &no);
28+
for (i = 0; i < no; i++)
29+
{
30+
scanf_s("%d", &A[i]);
31+
}
32+
selectionsort(A, no);
33+
for (i = 0; i < no; i++)
34+
{
35+
printf("%d ", A[i]);
36+
}
37+
printf("\n");
38+
return 0;
39+
}

Diff for: Sorting Technique/06 SelectionSort.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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 SelectionSort(int A[], int n){
24+
for (int i=0; i<n-1; i++){
25+
int j;
26+
int k;
27+
for (j=k=i; j<n; j++){
28+
if (A[j] < A[k]){
29+
k = j;
30+
}
31+
}
32+
swap(&A[i], &A[k]);
33+
}
34+
}
35+
36+
int main() {
37+
38+
int A[] = {3, 7, 9, 10, 6, 5, 12, 4, 11, 2};
39+
int n = sizeof(A)/sizeof(A[0]);
40+
Print(A, n, "\t\tA");
41+
42+
SelectionSort(A, n);
43+
Print(A, n, " Sorted A");
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)