I was trying to implement bubble sort algorithm to sort a 10 element array. I've tried writing the code below and it doesn't seem wrong, but it doesn't sort the elements at all.
Could someone give me a hand?
This is the code:
`
#include <stdio.h>
#define DIM 10
int main() {
int arr[DIM] = {1, 5, 6, 8, 7, 9, 3, 2, 4, 10};
int tmp;
puts("Original array: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
}
puts("");
puts("Ascending order arrray: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
puts("");
}
`
In the second loop, j should be used instead of i
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
Use j in the body of the second loop instead of i.`
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
#include <stdio.h>
#define DIM 10
int main() {
int arr[DIM] = {1, 5, 6, 8, 7, 9, 3, 2, 4, 10};
int tmp;
puts("Original array: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
puts("");
puts("Ascending order arrray: ");
for (int i = 0; i < DIM; i++) {
printf("%d", arr[i]);
}
puts("");
}
*Change: need to use "j" inplace of "i" in the 2nd for loop statements.
Related
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);
}
#include<stdio.h>
int main(void)
{
int array[10] = { 10,2,9,4,5,6,7,8,3,1 };
/*Implementing Bubble Sort */
int temp;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10 - i; j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
}
When I try to run the program I'm getting values sorted but one value has some garbage value and the dialogue box appears that stack around variable is corrupted in VS 2019. In some other compiler I'm getting 0 in place of 10 in compiler.
The inner for .loop
for (int j = 0; j < 10 - i; j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
invokes undefined behavior because when j is equal to 9 for the first iteration of the outer loop that is when i is equal to 0 the index in the expression array[j + 1] can be equal to 10 that results in accessing the memory beyond the array.
Rewrite the loop like
for (int j = 1; j < 10 - i; j++)
{
if (array[j-1] > array[j])
{
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
You can you this logic slightly edited from yours.
#include<stdio.h>
int main(void)
{
int array[10] = { 10,2,9,4,5,6,7,8,3,1 };
/*Implementing Bubble Sort */
int temp;
for (int i = 0; i < 10; i++)
{
for (int j = i; j < 10; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
}
I have written a C-program to generate random numbers and then sort them with the bubblesort-algorithm.
However, printing out the numbers (by an array, see the code) will show that the first element is 63, no matter what the randomly generated numbers were.
What causes this? And is there a more elegant way to bypass this than just skipping the first element of the list?
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("\n%d", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
for (int i = 0; i < 10; i++) {
printf("\n%d", list[i]);
}
In the inner loop of these loops
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
there is an access to the non-existent element of the array with the index 10
list[j] = list[j + 1];
^^^^^^
when j is equal to 9.
It si better to write the loop like
for (int j = 1; j < (10 - i); j++) {
if (list[j - 1] > list[j]) {
cache_num = list[j];
list[j] = list[j - 1];
list[j - 1] = cache_num;
}
You are going one past the array when the variable j reaches the value of 9. Use (10 - i - 1) to resolve the issue:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("%d\n", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i - 1); j++) { // note here ...
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
putchar('\n');
for (int i = 0; i < 10; i++) {
printf("%d\n", list[i]);
}
return 0;
}
Here in the following line you are going out of bounds because of which your are getting garbage value and thus altering your final result. Ex: when i=0 and j=9, this loops terminating condition will be is 9 < 10-0 which is true and it will execute. But for list [ j + 1 ] it will go out of bounds because there is no list [ 10 ].
for (int j = 0; j < (10 - i); j++){ ... }
It should have condition with -1 , (10-i-1)
for (int j = 0; j < (10 - i - 1); j++) { ... }
Instead of your implementation of the bubble sort to sort the data of 10 elements, you can use the below implementation.
The idea behind is that when you analyze (which you should) how the bubble-sort algorithm basically sorts the data, you will see a pattern i.e. in each pass of the inner-loop, the largest element (in-case of sorting the data in increasing order) will automatically go to its right location so, you don't need to consider that element again as it is already in its right position.
#include <stdio.h> // For basic I/O functions.
#include <stdlib.h> // For srand() & rand() functions.
#include <time.h> // For time(NULL) functions.
#define MAX_ARRAY_SIZE 10
int main(void) {
int list[10];
srand(time(NULL));
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
list[i] = rand();
}
// Implementation of Bubble-Sort
for(int i = (MAX_ARRAY_SIZE - 1); i >=0; --i) {
bool is_sorted = true;
for(int j = 0; j < i; ++j) {
if(list[j] > list[j + 1]) {
int cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
is_sorted = false;
}
}
if(is_sorted) {
break;
}
}
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
P.S: As you are sorting only 10 elements, using bubble-sort is not going to make any difference, but I suggest you use insertion-sort instead of bubble-sort because insertion-sort is faster for small-size arrays.
Refer: Comparison Between Bubble-Sort/Selection-Sort/Insertion-Sort.
For Some Fun: Watch this bubble sort algorithm dance. π
How do I make it so after the first pass, the largest number is guaranteed to be in the highest-numbered element of the array; after the second pass, the two highest numbers are βin place,β and so on.
The current code only makes it pass from largest to smallest but I do not want that.
I'm only trying to do this for the data items in original order.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main(void)
{
int a[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
int noc = 0;
puts("Data items in original order");
for (int noc = 0; noc < 9; noc++) {
printf("\n");
for (size_t i = 0; i + noc < SIZE; i++) {
printf("%4d", a[i]);
}
for (int pass = 1; pass < SIZE; pass++) {
for (size_t i = 0; i < SIZE - pass; i++) {
if (a[i] > a[i - 1]) {
int hold = a[i];
a[i] = a[i - 1];
a[i - 1] = hold;
}
}
}
}
for (int pass = 1; pass < SIZE; pass++) {
for (size_t i = 0; i < SIZE - pass; i++) {
if (a[i] > a[i + 1]) {
int hold = a[i];
a[i] = a[i + 1];
a[i + 1] = hold;
}
}
}
puts("\nData items in ascending order");
for (size_t i = 0; i + noc < SIZE; i++) {
printf("%4d", a[i]);
}
puts("");
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main(void)
{
int a[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
int i;
int pass = 0;
while(pass < SIZE - 1){
int index = SIZE - pass - 1;
int MAX = a[index];
for(i=0;i<SIZE - pass;i++){
if(a[i]>MAX) {
MAX = a[i];
index = i;
}
}
a[index] = a[SIZE - pass - 1];
a[SIZE - pass - 1] = MAX;
for(i=0 ;i < SIZE ; i++ ) printf("%d ",a[i]);
printf("\n");
pass++;
}
}
You can use several sort algorithm for that
shellsort
bubblesort ( slowest alg )
heapsort
insertion sort
tree sort
QuickSort
There are a lot of sort algo that placed the integer asc or desc
How to reverse an array upto specified position in c#
static int[] ReverseArray(int[] arr, int i) {
int[] arrnew = new int[8];
int k = i;
for (int j = 0; j < k / 2; j++)
{
int temp = arr[j];
arr[j] = arr[k - j - 1];
arr[k - j - 1] = temp;
}
return arr;
}