What is the name of my sorting algorithm? - c

I have written a sorting algorithm. What is the name of this algorithm?
void sort(int *arr, size_t len) {
int flag = 1, temp;
while (flag != 0) {
flag = 0;
for (int i = 0, j = 1; i < len - 1; i++, j++) {
if (arr[i] > arr[j]) {
flag = 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

This is bubble sort: repeatedly loop over an array swapping adjacent elements and stop when nothing is swapped.

Related

Bubble sort, print array per pass

How can you print the array per iteration in Bubble sort?
So far this is my sort function and im not really sure about it:
void sortBubble(int *arr)
{
int i, j;
int temp;
for (i = 0; i < SIZE; i++)
{
for (j = i + 1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printArr(arr); //call print function to print sorted array
}
If you want something to happen on each iteration of a loop, it should be placed within the loop body.
void sortBubble(int *arr)
{
int i, j;
int temp;
for (i = 0; i < SIZE; i++)
{
for (j = i + 1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
printArr(arr);
}
}
It's also advisable to minimize the scope of variables. i, j, and temp do not need to be scoped at the function level.
void sortBubble(int *arr)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
printArr(arr);
}
}
One final note: you can optimize your bubble sort by keeping track of the number of swaps performed in the inner loop. If zero swaps are performed you know the array is already sorted and you can immediately return.
Bubble sort is O(n^2) in the worst case. Your implementation is always O(n^2). This small change can reduce it to O(n) in the best case scenario, or in the realistic scenario, somewhere in between.
void sortBubble(int *arr)
{
for (int i = 0; i < SIZE; i++)
{
int swaps = 0;
for (int j = i + 1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
swaps++;
}
}
printArr(arr);
if (swaps == 0 /* or !swaps */) return;
}
}

Something is wrong with my bubble sort output

This is just a normal bubble sort code, but something is wrong in it.
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int size, int *arr);
int main(void)
{
int *array, size;
printf("enter the amount of data: ");
scanf("%d", &size);
array = (int*)malloc(sizeof(int) * size);
for (int i = 0; i < size; ++i)
{
scanf("%d", &array[i]);
}
bubble_sort(size, array);
for (int i = 0; i <= size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
void bubble_sort(int size, int *arr)
{
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
if (arr[j] > arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
else if (arr[j] == arr[j + 1])
{
continue;
}
}
}
}
When I execute it, a zero appear in the output when it must be print 1 2 3
[my_username#my_computer bubble_sort]$ ./bubble_sort
enter the amount of data: 3
3 1 2
0 1 2 3
^
|
Where are this zero came from?
Well, it is not quite Bubble Sort.
To start, as pointed out in the comments: arr[j + 1] accesses the array with an invalid index - one past the end of the array when j is at its maximum value (size - 1).
The loop to print the array
for(int i = 0; i <= size; ++i)
has a similar off-by-one error. i < size is the desired condition.
Accessing an array out-of-bounds invokes Undefined Behaviour.
The else if block within the sort is superfluous.
The simplified variant of bubble sort is usually written as:
void bubble_sort(int *array, size_t length)
{
for (size_t i = 0; i < length; i++) {
for (size_t j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
Whereas the standard bubble sort stops if it makes a pass on the array without swapping.
void bubble_sort(int *array, size_t length)
{
int swapped;
do {
swapped = 0;
for (size_t i = 1; i < length; i++) {
if (array[i - 1] > array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
swapped = 1;
}
}
} while (swapped);
}
This can be optimized by observing that all elements after the last swap have already been sorted.
void bubble_sort(int *array, size_t length)
{
do {
size_t n = 0;
for (size_t i = 1; i < length; i++) {
if (array[i - 1] > array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
n = i;
}
}
length = n;
} while (length);
}

Can I simplify selection sort in C?

Selection sort in C usually written in the form of the following code below, introducing a min_pos variable in which is stored the index of the minimum number of the array in a particular step of a for loop:
void selectionsort(int A[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_pos = i;
for (int j = i + 1; j < n; j++)
{
if (A[j] < A[min_pos])
{
min_pos = j;
}
if (min_pos != i)
{
int temp;
temp = A[i];
A[i] = A[min_pos];
A[min_pos] = temp;
}
}
}
return;
}
But, Is it necessary to introduce this variable when we can get the same result using the following code?
void selectionsort(int A[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (A[j] < A[i])
{
int temp;
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
return;
}
Both functions achieve the same result but neither one is a correct implementation of selection sort. They implement a less efficient algorithm called exchange sort.
For selection sort, a single swap should be performed for each element in the array. This was probably the purpose of the min_pos variable in the first function.
Here is a modified version:
void selectionsort(int A[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_pos = i;
for (int j = i + 1; j < n; j++)
{
if (A[j] < A[min_pos])
{
min_pos = j;
}
}
if (min_pos != i)
{
int temp = A[i];
A[i] = A[min_pos];
A[min_pos] = temp;
}
}
}
Here's a wondeful explanation (unmodified) by owner of a youtube channel named : portfolio courses
Wow - this is an awesome question! :-) So the above algorithm will work too, but it just sorts the array in a different way. As to why we might not do it this way:
This is a video on selection sort, and the above algorithm is not selection sort (even though it's close to it). In selection sort we find the smallest/largest element in the unsorted portion and swap it with the leftmost unsorted algorithm. Other approaches may also work, but they will not be a selection sort anymore. The above approach will do many, many more swaps than required.
For comparison's sake, I modified this code here to test the two different algorithms: https://github.com/portfoliocourses/c-example-code/blob/main/selection_sort.c. I modified the code to count the number of swaps required (see the modifications below for Selection Sort and this New Algorithm you've made). Selection Sort required only 6 swaps, where as the code above required 31 swaps.
One of the reasons why Selection Sort is used is that it's helpful when the cost of performing a swap in terms of time is high: https://en.wikipedia.org/wiki/Sorting_algorithm#Selection_sort. I know it's Wikipedia, but see this quote: "It does no more than n swaps, and thus is useful where swapping is very expensive."
Selection Sort:
int num_swaps = 0;
for (int i = 0; i < length - 1; i++)
{
// find the position of the minimum element in the unsorted portion of
// the array
int min_pos = i;
for (int j = i + 1; j < length; j++)
if (a[j] > a[min_pos]) min_pos = j;
// if that element is NOT the element at index i, then swap that element
// with the element at index i
if (min_pos != i)
{
int temp = a[i];
a[i] = a[min_pos];
a[min_pos] = temp;
num_swaps++;
}
}
New Algorithm:
int num_swaps = 0;
for (int i=0; i<length-1; i++)
{
for (int j=i+1; j<length; j++)
{
if(a[i]>a[j])
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
num_swaps++;
}
}
}
I think both algorithms are not particularly efficient, a more efficient way to write them would be as below:
void selectionsort(int A[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_pos = i;
for (int j = i + 1; j < n; j++)
{
if (A[j] < A[min_pos])
{
min_pos = j;
}
}
if (min_pos != i)
{
int temp;
temp = A[i];
A[i] = A[min_pos];
A[min_pos] = temp;
}
}
return;
}
Notice how the min_pos variable is used as a temporary storage for the swapping position. This is beneficial since the swapping requires three operations while using min_pos only requires one operation.

Insertion Sort String Array, not sorting right

Hello this is my method for a String Array insertion sort. It is returning bogus results to the console. Mainly just one array element over and over. Any help what needs to be changed is greatly appreciated.Thank you.
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i - 1 ;
while (j >= 0 && a[j].compareTo(Value)> 0) {
a[j+1] = a[j];
j=j-1;
}
a[i+1] = Value;
}
}
The code below works.
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i;
while (j > 0 && a[j-1].compareTo(Value)> 1) {
a[j] = a[j-1];
j--;
}
a[j] = Value;
The problem is a[j+1] = a[j];
Your original a[j+1] would be lost, you just simply replace it, without moving it / storing it, it is just simply replaced by a[j] and get lost...
I would modify your code like the following:
Find the position of current value to be inserted, swap it with the element at that position, then swap back that element into correct position
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i - 1 ;
int p = i;
while (j >= 0 && a[j].compareTo(Value)> 0) {
p = j--;
}
// p now is correct position to be inserted
swap(a[p], a[i]);
// Now loop the original a[p] back to a[p+1]
for(int z = i; z > p; z--){
swap(a[z], a[z-1]);
}
}
}
check the code works fine
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
and to print the number i use function printNumbers(array)
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}

Strange Bubble sort behaviour

Can anyone explain why this bubble sort function doesn't work and why I lose numbers in my output? I'm very new to C, so please forgive me if this is something very obvious I have missed.
#include <stdio.h>
#include <stdlib.h>
int bubble(int array[],int length) {
int i, j;
int temp;
for(i = 0; i < (length); ++i) {
for(j = 0; j < (length - 1); ++j) {
if(array[i] > array[i+1]) {
temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
}
}
}
return 0;
}
int main() {
int array[] = {12,234,3452,5643,0};
int i;
int length;
length = (sizeof(array)/sizeof(int));
printf("Size of array = %d\n", length);
bubble(array, length);
for (i = 0; i < (length); ++i) {
printf("%d\n", array[i]);
}
return 0;
}
Output
Size of array = 5
12
234
3452
0
0
In your inner loop, you don't use j at all. Double check your logic.
Also note that array[i+1] goes beyond the array boundary.
for (i = 0; i < (length-1); ++i) {
for (j = 0; j < (length-i-1); ++j) {
if(array[j] > array[j+1]) {
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
In a bubble sort you only use the inner loop variable.
Another thing, the inner loop goes from 0 to i if I remember well; but I think that's just an optimisation (as the tail is remains sorted in each step).
Try to run step by step your code with paper and pencil. That always works.
for (i = 0; i < (length); i++) {
for (j = 1; j < (length-i); j++) {
if(array[j-1] > array[j]) {
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}

Resources