Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions C/Language/Selection_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include<stdio.h>
void main()
{

int a[20],i,j,n,temp,s,pos;
printf("Enter n");
scanf("%d",&n);
printf("Enter elements in the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

/*using selection sort*/
for(i=0;i<n;i++){
s=a[i];
pos=i;
for(j=i;j<n;j++){
if(a[j]<s)
{
s=a[j];
pos=j;
}
}
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}

printf("Sorted array is:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);

}
43 changes: 43 additions & 0 deletions C/Language/insertionSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// C program for insertion sort
#include <math.h>

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this include it's not required

#include <stdio.h>

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can directly use for (int i = 0; i < n; i++) add a block { }

printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

after formating your code with the online formatter. make sure your array should be as it is int arr[] = { 12, 11, 13, 5, 6 };

int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}