Reputation: 39
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);
}
Upvotes: 3
Views: 155
Reputation: 621
I would say closer to insertion sort as you create sorted chunks by finding the first misfit. Rather than iterating whole array and pushing the largest element to the end (like in bubble sort)
It is closer to the standard version of insertion sort, where you swap elements until you find the right place in the sorted chunk. However, after you insert your element you start your index from wrong index, as it has created a sorted sub array.
This helps visualize the two sorting algorithms: https://visualgo.net/bn/sorting
Upvotes: 2
Reputation: 1648
This is a Bubble Sort
algorithm. Only difference between Bubble Sort
algorithm and your algorithm is that Bubble Sort
algorithm sorts the rightmost elements first and then so on and your algorithm is sorting the leftmost elements first.
Analysis:
Your Algo:
<---------
<--------
<-------
<------
<-----
<----
<---
<--
<-
<
Bubble Sort Algo:
------>
----->
---->
--->
-->
->
>
Upvotes: 0
Reputation: 744
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
Upvotes: 4