mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
Modify insertionSort for more clear
This commit is contained in:
parent
5d7caa8328
commit
cd813030ea
@ -2,29 +2,30 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/*Displays the array, passed to this method*/
|
||||
void display(int arr[], int n){
|
||||
|
||||
void display(int arr[], int n) {
|
||||
int i;
|
||||
for(i = 0; i < n; i++){
|
||||
printf("%d ", arr[i]);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
|
||||
}
|
||||
|
||||
/*This is where the sorting of the array takes place
|
||||
arr[] --- Array to be sorted
|
||||
size --- Array Size
|
||||
*/
|
||||
void insertionSort(int arr[], int size){
|
||||
int j,temp,i;
|
||||
for(i=0; i<size; i++) {
|
||||
temp = arr[(j=i)];
|
||||
while(--j >= 0 && temp < arr[j]) {
|
||||
arr[j+1] = arr[j];
|
||||
arr[j] = temp;
|
||||
void insertionSort(int arr[], int size) {
|
||||
int i, j, key;
|
||||
for(i = 0; i < size; i++) {
|
||||
j = i - 1;
|
||||
key = arr[i];
|
||||
/* Move all elements greater than key to one position */
|
||||
while(j >= 0 && key < arr[j]) {
|
||||
arr[j + 1] = arr[j];
|
||||
j = j - 1;
|
||||
}
|
||||
/* Find a correct position for key */
|
||||
arr[j + 1] = key;
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,22 +33,22 @@ int main(int argc, const char * argv[]) {
|
||||
int n;
|
||||
printf("Enter size of array:\n");
|
||||
scanf("%d", &n); // E.g. 8
|
||||
|
||||
|
||||
printf("Enter the elements of the array\n");
|
||||
int i;
|
||||
int arr[n];
|
||||
for(i = 0; i < n; i++){
|
||||
for(i = 0; i < n; i++) {
|
||||
scanf("%d", &arr[i] );
|
||||
}
|
||||
|
||||
|
||||
printf("Original array: ");
|
||||
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
|
||||
|
||||
display(arr, n);
|
||||
|
||||
insertionSort(arr, n);
|
||||
|
||||
|
||||
printf("Sorted array: ");
|
||||
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
|
||||
|
||||
display(arr, n);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user