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;
}
}
Related
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.
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);
}
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.
how remove this error tried everything....
this program is about finding 5 closest number from a array...
in main part i simply take array, num and size and passes through the function
void printclosest(int arr[], int x, int n)
{
int diff[30];
int i,j,k,p,a;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (arr[i] > arr[j])
{
a = arr[i];
arr[i] = arr[j];
arr[j] = a;
}
}
}
for(i=0;i<n;i++)
{
diff[i]=abs(a[i]-x);
}
for (k = 0; k < n; ++k)
{
for (p = k + 1; p < n; ++p)
{
if (diff[k] > diff[p])
{
a = arr[k];
arr[k] = arr[p];
arr[p] = a;
}
}
}
for(i=0;i<5;i++)
{ printf("%d",arr[i]);
}
}
a is declared as int, yet you try to use it as an array here:
diff[i]=abs(a[i]-x);
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;
}
}
}