Bubble Sort Algorithm in C - c

The program I"m trying to finish is a program using the bubble sort algorithm. I am not sure what is the problem or in which function the problem is in. The problem is the program does not sort the array in properly. (It also must be arranged in ascending order).
Here is the code:
#include <stdio.h>
#include "simpio.h"
void getArray (int arr[], int size);
void sortArray (int arr[], int size);
void swap (int arr[], int num, int number);
void dispArray (int arr[], int size);
bool checkBigger (int arr[], int num, int number);
main()
{
int size;
printf("Enter number of elements: ");
size=GetInteger();
int arr[size];
getArray(arr, size);
sortArray(arr, size);
dispArray(arr, size);
getchar();
}
void getArray (int arr[], int size)
{
int num;
printf("Please enter the value of the elements: \n");
for(num=0; num<size; num++)
{
arr[num]=GetInteger();
}
}
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=num+1;
checkBigger(arr, num, number);
}
}
}
void swap (int arr[], int num, int number)
{
int tem;
tem=arr[num];
arr[num]=arr[number];
arr[number]=tem;
}
void dispArray (int arr[], int size)
{
int num;
printf("The sorted list is:\n");
for(num=0; num<size; num++)
{
printf("%d\t", arr[num]);
}
}
bool checkBigger (int arr[], int num, int number)
{
if(arr[num]>arr[number])
{
swap(arr, num, number);
}
}
Thank you very much.

void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=d+1;
checkBigger(arr, d, number);
}
}
}

pretty sure your problem is with you algorithm, try to simulate your algorithm in pen and paper. it will help your understanding of your code and the algorithm better :)
for your convenience here i am including a bubble sort algorithm i did some while ago
void bubbleSort( int a[], int n)
{
int i,j,temp; // for a={1,2,3,4,5} n is 5
n = n - 1; // bcz otherwise it will get out of index
for(i=0; i<n; i++)
{
for(j=0; j<n-i; j++)
{
if(a[j]>a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
}
i hope this helps

All I follow from the above examples is an implementation of the exchange sort.
The exchange sort on the outer loop checks each entry in the table against the first element, exchanging when necessary. At then end of the inner loop, the lowest element is in position 1, then it begins with position 2, comparing it to the remaining elements, and doing an exchange. Even if the array was already in order, the sort cannot stop. It has to do a n*(n-1) compares. An array of 50 elements, already sorted will do 50*49 comparisons.
The bubble sort works differently
set a swap flag to zero. Then
slide along the array, comparing position(i) to position(i+1). If a swap takes place, you do the sort again.
here is some pseudo code.
swap = 0
do {
for (i=o;i< no-elements-1;i++) {
if (array[i] > array[i+1])
{
do the exchange
set swap=1
}
/**/
} while (swap == 1);
The above illustrates the bubble sort.
Note. if the data is in order, there is no swap and there is no second loop. The sort algorithm is able to quit early.
if a fifty element array is in order, the sort would have done 50 comparisons and would have stopped.
The exchange sort, which is described earlier would have to do 50*49 or 2450 comparisons.

// BUBBLE SORT.
#include <stdio.h>
#define MAX 20
int main()
{
int arr[MAX];int no;
printf("PLEASE ENTER THE CURRENT SIZE OF THE ARRAY\n");
scanf("%d",&no);
int i;
printf("PLEASE ENTER THE ELEMENTS OF THE ARRAY\n");
for(i=0;i<no;i++)
scanf("%d",&arr[i]); /*reading the elements*/
/* sorting begins*/
int j,k,l;
int temp;
int flag=0;
for(k=0;k<no-1;k++)
{
flag=0;
j=k;
for(i=0;i<no-j-1;i++) /* not going to the part that has been sorted*/
{
if(arr[i]>arr[i+1])
{
flag=1;
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
else
continue;/* not necessary*/
}
if(flag==0) /*implies that the array is alraedy sorted*/
break;
}
printf("THE SORTED LIST:\n\n");
for(i=0;i<no;i++)
printf("%d\n",arr[i]);
}

Related

Finding specific sum of a integers in an array

Basically this problem asks me to get an input of target_sum and check the integers in the array. If a sum of a pair is equal to target_sum, I need to print it.
I wrote the code like this but it does not work. Where did I make the mistake?
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++){
for (j=0;j<size;j++){
if (arr[i] + arr[j] == target_sum)
{
printf("(%d,%d)",arr[i],arr[j]);
}
else
{
printf("No pair.");
}
}
}
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",target_sum);
findPair(arr,6,target_sum);
}
As #nsilent22 suggested, scanf("%d",target_sum); should be changed into scanf("%d",&target_sum);. Besides that, you could have the second for loop start at j=i+1, making your code overall look like this:
#include <stdio.h>
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++)
for (j=i+1;j<size;j++)
if (arr[i] + arr[j] == target_sum)
printf("\n(%d,%d)",arr[i],arr[j]);
else
printf("\nNo pair.");
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",&target_sum);
findPair(arr,6,target_sum);
}

Random Selection -i'th order statistic

The random selection program below doesn't find the i'th order statistic. The following program follows the algorithm provided in Cormen's Introduction to Algorithm. Thanks in advance for finding the bug.
#include<stdio.h>
#include<stdlib.h>
int random(int a,int b) //generates random numbers [a,b]
{
return a+(rand()%(b-a+1));
}
void swap(int *a,int *b) //swwaps the elements
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int partition(int a[],int p,int r) //partitioning similar to that of quicksort
{
int i=p-1,j,x=a[r];
for(j=p;j<r;j++)
{
if(a[i]<x)
{
i++;
swap(&a[i],&a[j]);
}
}
swap(&a[i+1],&a[r]);
return i+1;
}
int random_partition(int a[],int p,int r) //random index generation whose element gets swapped with the last element of the array
{
int q=random(p,r);
swap(&a[q],&a[r]);
return partition(a,p,r);
}
int random_selection(int a[],int p,int r,int index) //finds the i'th order statistic
{
if(p==r)
return a[p];
if(p<r)
{
int mid,k;
mid=random_partition(a,p,r);
k=mid-p+1;
if(k==index)
return a[mid];
if(index<k)
return random_selection(a,p,mid-1,index);
if(index>k)
return random_selection(a,mid+1,r,index);
}
}
main()
{
int a[50],i,size,index;
printf("enter the size of the array\n");
scanf("%d",&size);
printf("enter the array elements\n"); //takes array elements input
for(i=1;i<=size;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=size;i++) //prints the index of each element
{
printf("%d\n",random_selection(a,1,size,i));
}
}
Do you need a srand() in your main()? Just like these threads
Recommended way to initialize srand?
and How does srand relate to rand function?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, n;
time_t t;
n = 5;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 50);
}
return(0);
}

Selection sort program in C

This is one of the programs, where a set of numbers are sorted into ascending order, by finding the largest number in the range between the left point and the end of the array, then moving that element into its correct index position by switching the elements. My problem is that it is not in ascending order, as the numbers in between don't get ordered, and I'm wondering how to fit that in the program.
Here is my code at the moment:
#include <stdio.h> /* Library inclusions */
#include "genlib.h"
#include "simpio.h"
#define size 7 /* Constants */
void sortArray (int numbers[]); /* prototypes */
int indexMax (int numbers[], int low, int high);
void swap (int numbers[], int loc, int loc1);
void getArray (int numbers[]);
void displayArray (int numbers[]);
main()
{
int numbers[size];
getArray(numbers);
sortArray(numbers );
displayArray (numbers);
getchar();
}
void getArray (int numbers[]) /*Function getArray*/
{
int i;
for (i=0; i<size; i++)
{
printf ("Enter an integer? ");
numbers[i]=GetInteger();
}
}
void displayArray (int numbers[]) /*Function displayArray*/
{
int i;
printf ("\n The sorted list is: \n");
for (i=0; i< size; i++)
{
printf ("%d\t", numbers[i]);
}
}
void sortArray (int numbers[]) /*Function sortArray*/
{
int i , maxInd;
for (i=0; i<size;i++)
{
maxInd = indexMax (numbers, i, size-1);
swap (numbers, size-1, maxInd);
}
}
int indexMax (int numbers[], int low, int high) /*Function indexMax*/
{
int i, maxInd;
maxInd=high;
for (i=low;i<=high;i++)
{
if (numbers[i]>numbers[maxInd])
{
maxInd =i;
}
}
return (maxInd);
}
void swap (int numbers[], int loc, int loc1) /*Function swap*/
{
int temp;
temp=numbers[loc];
numbers[loc]=numbers[loc1];
numbers[loc1]=temp;
}
Thank you very much. :)
You SortArray function logic is wrong. You are finding maxindex from i to last index and replacing it with last index and then increment i. In first iteration the largest number reaches end thereafter in subsequent iterations, the last index only will be selected as maxindex and no change in array will be there.
Instead you always need to iterate from first index and upto one index less than previous last index.
void sortArray (int numbers[]) /*Function sortArray*/
{
int i , maxInd;
for (i=size-1; i>=0;i--)
{
maxInd = indexMax (numbers, 0, i);
swap (numbers, i, maxInd);
}
}
In indexMax function change greater than (>) to less than (>).
There may be something wrong in the function sortArray()
void sortArray (int numbers[])
{
int i
int maxInd;
for (i=0; i<size;i++)
{
maxInd = indexMax (numbers, i, size-i-1);
swap (numbers, size-1-i, maxInd);
}
}
I make a small change, and it worked!!

Selection sort on array in C

I'm trying to create a simple(?) selection sort program in C that selects the largest integer of an integer array and places it in the location a[n-1], places the second largest number in a[n-2], etc until the smallest number is placed in a[0]. I've run through the below code on paper and it seems like it should work, but when I compile it I'm getting faulty results. Am I missing something obvious?
/* The program implements selection sort*/
#include <stdio.h>
#include "simpio.h"
#define n 5
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
void PrintArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
PrintArray(a);
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,i);
swap(a,max,(n-1-i));
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=high;i<n;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
void PrintArray(int a[])
{
int i;
for(i=0;i<n;i++)
printf("a[%d]=%d\n", i, a[i]);
}
Change these method to:
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
I actually tested my answer and it works.
Selection sort is process of comparing minimum element from the list and placing from the least index.
Now consider below code snippet.
public void selectionSort(int[] elements) {
for(int i=0;i<elements.length;i++) {
int minPosition = i;
for(int j=i+1;j<elements.length;j++) {
if(elements[minPosition]>elements[j])
minPosition = j;
}
int temp = elements[i];
elements[i] = elements[minPosition];
elements[minPosition] = temp;
}
}
Thanks for reading, let me know feedback to improve from myside
Shouldn't:
max=FindMax(a,i);
swap(a,max,(n-1-i));
Be:
max=FindMax(a,i);
swap(a,max,i);
otherwise, next time through the loop, you'll find the same max value in the top position in the array.
A very basic implementation of selection sort
#include<stdio.h>
main()
{
int i,j,n=7,a[]={1,2,5,3,8,9,5},key;
for(j=1;j<n;j++)
{
key=a[j]; //a[j] is the new element to be added to the sorted
//sequence
i=j-1;
while(i>=0 && key<a[i]) //traverse through the sorted sequence
{a[i+1]=a[i];i--;} //until the place of key is found
a[i+1]=key;
}
for (j=0;j<n;j++)
printf("%d",a[j]);
}
#include<stdio.h>
#include<conio.h>
int removex(int arr[],int small,int n)
{
int i=0;
for(;i<n;i++)
if(arr[i]==small) //searching that no to delete
break;
for(;i<n-1;i++)
arr[i]=arr[i+1]; //delete by overloading no
return n-1;
}
void selectSort(int arr[],int sort[],int n)
{
int j=0,k=0,small;
while(n!=0)
{
small=arr[0];
for(j=0;j<n;j++)
if(arr[j]<small)
small=arr[j]; //finding smallest no
sort[k++]=small;
n=removex(arr,small,n); //removing that from list as we included that no into sorted list
}
}
void main()
{
int arr[10],arr2[10],i,n;
clrscr();
printf("Enter how many elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectSort(arr,arr2,n);
printf("sorted list is\n");
for(i=0;i<n;i++)
printf("%d\n",arr2[i]);
getch();
}

mergesort C implementation

i wrote this code in C language on Xcode following the algorithm of mergesort.
The problem is that sometimes i get EXC_BAD_ACCESS and i can't manage where the error is!
The merge algorithm should work (i tried it outside the mergesort function and works!). Thank you for your help and patience!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIM 6
void mymerge (int v[], int i1,int i2, int last); //mergesort core: merge two ordinated arrays in one bigger ordinated array
void mymergesort (int v[], int lower, int upper);//mergesort
void printv (int v[],int lower, int upper);
int main () {
int i;
srand((unsigned int)time(NULL));
int v[DIM];
for (i=0; i<DIM; i++)
v[i]=rand()%15;
printv(v, 0, DIM-1);
getc(stdin);
mymergesort(v, 0, DIM-1);
printv(v, 0, DIM-1);
}
void printv (int v[],int lower, int upper){
int i;
for (i=lower; i<=upper; i++)
printf("%d\t",v[i]);
}
void mymergesort (int v[], int lower, int upper){
int mid=(upper+lower)/2;
if (upper<lower) {
mymergesort(v, lower, mid);
mymergesort(v, mid+1, upper);
mymerge(v,lower,mid+1,upper);
}
}
void mymerge (int v[], int i1,int i2, int last){
int i=i1,j=i2,k=i1,*vout;
vout=(int*)malloc((last-i1+1)*sizeof(int));
while (i<i2 && j<=last) {
if (v[i]<=v[j]) {
vout[k++]=v[i++];
}else {
vout[k++]=v[j++];
}
}
for (;i<i2;i++) vout[k++]=v[i];
for (;j<=last;j++) vout[k++]=v[j];
for (k=i1; k<=last; k++) v[k]=vout[k];
free(vout);
}
EDIT:
thank you very much! but i think think there is another problem, when I try to sort a bigger array (200 elements), the program doesn't work (i get a malloc error: incorrect checksum for freed object - object was probably modified after being freed). But if I run it from the xCode debugger everything works fine
This: vout=(int*)malloc((last-i1)*sizeof(int)); is wrong.
First, the number of elements you want is last-i1+1, not last-i1 - classic off-by-1. This kind of error is one of the reasons why the convention in C code is to make lower bounds inclusive and upper bounds exclusive - less +1 and -1 you need to do, less opportunity to screw up.
The more serious error is that you index vout starting from i1. If you do it this way, you need to allocate last+1 element for vout, and you never use the first i1 (index 0 .. i1-1).
Fix: First, allocate last-i1+1 elements. Second, initialize k to 0 at the beginning, not i1. Third, change the final copy to be
for (k=i1; k<=last; k++) v[k] = vout[k-i1];
You have two problems. The first is that your calculation of the midpoint is incorrect - you use (upper - lower)/ 2, but this is not guaranteed to lie between lower and upper. What you actually want is lower + (upper - lower) / 2. It's also not necessary to do any work if there's only 1 number in the interval to be sorted - so the mymergesort() function should look like:
void mymergesort (int v[], int lower, int upper)
{
if (upper > lower) {
int mid = lower + (upper - lower)/2;
mymergesort(v, lower, mid);
mymergesort(v, mid+1, upper);
mymerge(v,lower,mid+1,upper);
}
}
The second problem is the one in the mymerge() function already pointed out by Fabian Giesen.
#include<stdio.h>
#include<stdlib.h>
void merge(int *a, int n1, int *b, int n2, int *arr)
{
int i=0, j=0, n=0;
while(i<n1 && j<n2)
{
if (a[i] < b[j])
{
arr[n++] = a[i];
i++;
}
else
{
arr[n++] = b[j];
j++;
}
}
while( i < n1)
arr[n++] = a[i++];
while( j < n2)
arr[n++] = b[j++];
}
void merge_sort(int *a, int n)
{
int left[n/2], right[n-n/2],i=0;
if (n<=1)
return ;
while(i<n/2)
left[i] = a[i++];
while(i<n)
right[i - n/2] = a[i++];
merge_sort( left, n/2 );
merge_sort( right, n-n/2);
merge(left, n/2, right, n-n/2, a);
}
void main()
{
int a[] = { 6, 5, 3, 1,9, 8, 7, 2, 4},i;
merge_sort(a,sizeof(a)/sizeof(a[0]));
for(i=0;i<9;i++)
printf("--%d",a[i]);
printf("\n");
}
-- s.k
#include<stdio.h>
#include<conio.h>
#define max 20
/*** function for merging the adjecent subarrays in sorted order ***/
void merge(int A[max],int n,int low,int high, int mid)
{
int i=low,j=mid+1,k,temp;
while((i<=j)&&(j<=high))
{
if(A[i]>A[j]) /** if element of the second half is greater then exchg and shift **/
{
temp=A[j];
for(k=j;k>i;k--) /** shifting the elements **/
{
A[k]=A[k-1];
}
A[i]=temp;
j++;
}
i++;
}
}
/******* iterative function for merge sort ********/
void merge_sort(int A[max],int n,int low,int high)
{
int mid;
if(low<high) /** terminating condition **/
{
mid=(high+low)/2; /** calculating the mid point ***/
merge_sort(A,n,low,mid); /*** recursive call for left half of the array ***/
merge_sort(A,n,mid+1,high); /*** recursive call for right half of the array ***/
merge(A,n,low,high,mid); /** merging the both parts of the array **/
}
}
/******* begening of the main function **********/
int main()
{
int A[max],n,i;
/** reading the inputs fro users **/
printf("\n enter the size of the array\n");
scanf("%d",&n);
printf("\n enter the array \n");
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
/*** calling merge sort ***/
merge_sort(A,n,0,n-1);
/** printing the sorted array **/
for(i=0;i<10;i++)
{
printf("\n\t%d",A[i]);
}
getch();
return 0;
}

Resources