Selection sort on array in C - 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();
}

Related

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);
}

Merge sort not showing correct output

I have implemented each line of merge sort algorithm-wise and can't find error.
al and ar are left and right sub arrays. Arrays are passed along with size.
#include<stdio.h>
#include<conio.h>
void mergesort(int a[] ,int);
void merge(int al[],int,int ar[],int,int a[]);
int main()
{
int i,n;
printf("Enter the no of elements to be sorted\n");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
mergesort(a,n);
printf("\nThe elements after sorting are:");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
return 0;
}
void mergesort(int a[],int size)
{
int i,n=size,mid;
if(n<2)
return;
mid=n/2;
int left[mid],right[n-mid];
for(i=0;i<mid;i++)
left[i]=a[i];
for(i=mid;i<n;i++)
right[i]=a[i];
mergesort(left,mid);
mergesort(right,n-mid);
merge(left,mid,right,n-mid,a);
}
void merge(int al[],int sl,int ar[],int sr,int a[])
{
int i=0,j=0,k=0;
while(i<sl && j<sr)
{
if(al[i]<=ar[j])
{
a[k]=al[i];
i++;
}
else
{
a[k]=ar[j];
j++;
}
k++;
}
while(i<sl)
{
a[k]=al[i];
i++;
k++;
}
while(j<sr)
{
a[k]=ar[j];
j++;
k++;
}
}
input:
no of elements:4
5 6 3 1
output:
5 16 16 16
Look at this part of your code:
int left[mid],right[n-mid];
for(i=0;i<mid;i++)
left[i]=a[i];
for(i=mid;i<n;i++)
right[i]=a[i];
You are accessing the right array with indexes beyond the array bounds. That should be something like this instead:
right[i - mid]=a[i];
I have correct code for merge sort written in C. Please tally with it.
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50];
int i,j,k;
i=i1;
j=i2;
k=0;
while(i<=j1 && j <=j2)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1)
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

Merge two arrays without sorting using array

I am trying to merge to arrays without sorting (add one then another) using pointer method but its just printing the first array and then garbage values. What i am trying to do is just combine 2 arrays in one big array. No sorting required(at least for now).
void getarray(int*,int);
int merge(int*,int*,int,int,int*);
main()
{
int a[10],b[10],c[20];
int i,j,n,m,size;
clrscr();
printf("Enter no. of elements in FIRST array: ");
scanf("%d",&n);
getarray(a,n);
printf("Enter no. of elements in SECOND array: ");
scanf("%d",&m);
getarray(b,m);
merge(a,b,n,m,c);
printf("\nMerged Array: \n");
for(i=0;i<n+m;i++)
{
printf("\t%d\t",c[i]);
}
getch();
return 0;
}
void getarray(int *x, int y)
{
int i;
for(i=0;i<y;i++)
{
scanf("%d",x+i);
}
}
int merge(int *a, int *b,int n,int m,int *c)
{
int i,j;
for(i=0;i<n;i++)
{
*(c+i) = *(a+i);
}
for(j=i;j<i+m;j++)
{
*(c+j) = *(b+j);
}
}
Alternatively you can use (assuming c is large enough):
void merge(int *a, int *b,int n,int m,int *c) {
memcpy(c, a, sizeof(int)*n);
memcpy(c+n, b, sizeof(int)*m);
}
You would need to include string.h.
int merge(int *a, int *b,int n,int m,int *c)
{
int i,j;
for(i=0;i<n;i++)
{
*(c+i) = *(a+i);
}
for(j=0;j<m;j++)
{
*(c+n+j) = *(b+j);
}
}

Bubble Sort Algorithm in 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]);
}

MergeSort - Compiling but not giving any output

This is based on the algorithm given in the Cormen's book. What am I doing wrong?
#include <stdio.h>
#include <conio.h>
void mergesort(int a[],int,int);
void merge(int a[],int,int,int);
int main()
{
int i,num,a[50];
printf("Enter the number of elements : ");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("\n%d) ",i);
scanf("%d",&a[i]);
}
mergesort(a,1,num);
for(i=1;i<=num;i++)
{
printf("SoRTED ArrAy \n");
printf("\n%d) ",a[i]);
}
getch();
return 0;
}
void mergesort(int a[],int i, int k)
{
int j;
j=(i+k)/2;
while(i<k)
{
mergesort(a,i,j);
mergesort(a,j+1,k);
merge(a,i,j,k);
}
}
void merge(int a[],int p,int q,int r)
{
int i,j,k,n1,n2;
n1=q-p+1;
n2=r-q;
int l[n1],s[n2];
for(i=1;i<=n1;i++)
{
l[i]=a[p+i-1];
}
for(j=1;i<=n2;j++)
{
s[j]=a[q+j];
}
l[n1+1]=1000;
s[n2+1]=1000;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(l[k]<s[k])
{
a[k]=l[i];
i++;
}
else
{
a[k]=s[j];
j++;
}
}
}
The main issue is that i and k are never updated inside your while loop in the mergesort function, leading to an infinite loop. It's likely that you don't even need the while loop.
void mergesort(int a[],int i, int k)
{
int j;
j=(i+k)/2;
while(i<k)
{
mergesort(a,i,j);
mergesort(a,j+1,k);
merge(a,i,j,k);
}
}
Nothing inside the while changes the value of i or k. So if i<k, the loop will repeat forever.

Resources