I have written this code by understanding the insertion sort algo. My teacher says its bubble sort but my friends are saying it is insertion. Could someone please check and brief me on this.
#include <stdio.h>
void sort(int n) {
int i, j;
float arr[n], k;
for (i = 0; i <= n - 1; i++) {
printf("Enter the number");
scanf("%f", &arr[i]);
}
for (i = 1; i <= n - 1; i++) {
j=i
while (arr[j] < arr[j - 1] && j > 0) {
k = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = k;
/*printf("\n\t%f",arr[j]);*/
j--;
/*printf("\n%d",j);*/
}
/*printf("\n%d",x[i]);*/
}
for (i = 0; i < n; i++) {
printf("\n%f", arr[i]);
}
}
int main() {
int t;
printf("Enter the number of values to be sorted");
scanf("%d", &t);
sort(t);
}
Looks like both/neither for me. It may be insert sort, because you always take first element in unsorted part of array and puts it into correct place in sorted part of array. However, insertion is not done by moving all necessary elements 1 element right and then inserting selected element to correct place (which i would say, standard insert sort does), but instead it swaps selected element with 1 element to the left, until selected element is in correct place.
Because of "sorted" and "unsorted" part of array, I would say insert sort.
Because of swapping neighbour elements, I would say bubble sort.
However, it seems more like insert sort to me. If instead of (inefficient) swapping, you would instead only move left element to right, and only finally write selected element to left (final, correct position of selected element), It would be a nice insert sort
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With