Pointers in C while using array and swap function - c

I had a doubt in using pointers
For example I made this swapping program and to swap so i have to use pointers in order to maintain same address where swapping is happening
#include<stdio.h>
int swap(int *x,int *y); //swapping function
int main()
{
int a,b;
scanf("%d %d",&a,&b);
printf("A->%d,B->%d\n",a,b); //print original array
swap(&a,&b); //pass by reference
printf("A->%d,B->%d\n",a,b); //print sorted array
}
int swap(int *x,int *y)
{
int temp; // Swapping
temp =*x;
*x=*y;
*y=temp;
}
Then I wrote a program for merge sort. Here I just passed the value (pass by value) in the funtions without using pointers but when I print the sorted array in the main function it is sorted.
#include<stdio.h>
void merge(int a[],int start,int mid,int end); //Sorting and merging lists
void mergesort(int a[],int start,int end); //Dividing the list
int main()
{
int size,i;
scanf("%d",&size);
int arr[size];
for(i=0;i<size;i++) //Input array
{
scanf("%d",&arr[i]);
}
printf("Array is: ");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]); //print original array
}
printf("\n");
mergesort(arr,0,size-1); //Mergesort call-pass by value
printf("Sorted Array is: ");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]); //print sorted array
}
printf("\n");
}
void mergesort(int a[],int start,int end)
{
int mid;
if(start<end)
{
mid=(start+end)/2; //calculating mid and dividing array recursively
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid+1,end);
}
}
void merge(int a[],int start,int mid,int end)
{
int b[end]; //auxillary array
int i;
int p=start,q=mid,k=start;
while((p<mid) && (q<=end)) //comparing both list
{
if(a[p]<=a[q])
{
b[k++]=a[p++];
}
else
{
b[k++]=a[q++];
}
}
while(p<mid) //adding remaing items to auxillary array
{
b[k++]=a[p++];
}
while(q<=end) //adding remaing items to auxillary array
{
b[k++]=a[q++];
}
for(i=start;i<k;i++) //copying items from auxillary array to original array
{
a[i]=b[i];
}
}
Why is this happening ?

You can't directly pass arrays by value in C (best you can do is wrap a fixed-size array in a struct). In a parameter list int a[] is exactly equivalent to int *a.
So you are using pointers and that's why the array is sorted.

In C and similar languages the first array dimension of a function parameter is rewriten as a pointer. So your interfaces
void merge(int a[],int start,int mid,int end);
void mergesort(int a[],int start,int end);
are exactly the same as
void merge(int* a,int start,int mid,int end);
void mergesort(int* a,int start,int end);
So actually for arrays, you always pass an address to your function.

I don't know why you say:
Here I just passed the value (pass by value) in the funtions without using pointers.
because, when you use
mergesort(int a[],int start,int end)
merge(int a[],int start,int mid,int end)
Then a[] is as same as when you use *a. It is using the pointer way.

Related

Quicksort: Why wrong output

I want to sort the given array using quicksort.
So I wrote this code in c for quicksort algorithm but its not giving me correct answer.Its giving me the same output as the input.
eg: If i give input as
3
2
1
then it is giving
Output:
3
2
1
Please help and tell me where is the mistake.
#include<stdio.h>
void quicksort(int a[],int p,int r);
int partition(int a[],int p,int r);
void swap(int a,int b);
int main()
{
int n,i,p,r;
printf("ENter no of elements");
scanf("%d",&n);
int a[n];
printf("ENter the elements");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
p=1;
r=n;
quicksort(a,1,n);
printf("\n");
for(i=1;i<=n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}
void quicksort(int a[],int p,int r)
{
int q;
if(p<r)
{
q = partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
int partition(int a[],int p,int r)
{
int x,i,j;
x=a[r];
i=p-1;
for(j=p;j<=r-1;j++)
{
if(a[j]<=x)
{
i=i+1;
swap(a[i],a[j]);
}
}
swap(a[i+1],a[r]);
return (i+1);
}
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
}
void swap(int a,int b)
This line is taking the two parameters as copies of the values. The swapping is done on he copies.
void swap(int* a, int* b)
This is the C-style of passing parameters by reference. You need to pass the references then:
swap(&a[i], &a[j]);

quicksort implementation trouble

I am encountering the problems in executing the quicksort algorithm.
THere is a error i am encountering but unable to find where the problem is. if someone could point where the error is i will be thankfull.
#include <stdio.h>
#include <stdlib.h>
void main(){
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr,0,n-1);
printArray(arr,0,n-1);
}
//Quicksort Function
void quickSort(int arr[],int low,int high){
if (low < high){
int pi=partition(arr,low,high);
quickSort(arr,low,pi-1);//takes care of lower set of numbers
quickSort(arr,pi+1,high);//takes care of higher elements above pivot
}
}
//Function for partitioing, in my program i am cosidering pivot as the element at high or the last element
int partition(int arr[],int low,int high){
int i,j;
i=(low-1);
int pivot=arr[high];
for(j=low;j<=high;j++){
if(arr[j]<=pivot){
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[high]);
return (i+1);
}
//function to print array
void printArray(int arr[],int low,int high){
int i;
for(i=low;i<=high;i++){
printf("%d ",arr[i]);
}
}
//function to swap two elements of array
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
The Simple Implementation of QuickSort Algorithm
void q_sort(int v[],int left,int right)
{
int i,last;
if(left>=right)
return;
swap(v,left,(left+right)/2);
last=left;
for(i=left+1;i<=right;i++)
if(v[i]<v[left])
swap(v,++last,i);
swap(v,left,last);
q_sort(v,left,last-1);
q_sort(v,last+1,right);
}
void swap(int v[],int i,int j)
{
int temp;
if(i!=j){
temp=v[i];
v[i]=v[j];
v[j]=temp;
}
}
The problem is in this statement of your partition() -
if(arr[j]<=pivot){
Change it to -
if(arr[j]<pivot){

Merge sort in C

I am new in programming/C.
I understand the algorithm of merge-sort as an algorithm but when it comes to programming, it appears that I am doing something wrong.
Could anybody help?
Thanks.
Here is my code:
merge(int A[],int p,int q,int r);
part(int A[],int p,int r);
int main()
{
int A [6]={10,5,4,0,11,7}, n,y,z;
y=1; z=sizeof(A)/sizeof(int);
part(A,y,z);
for(n=0;n<z;n++)
printf("%d\n", A[n]);
return 0;
}
part(int A[],int p,int r)
{
if (p<r)
{
int q=(p+r)/2;
part(A,p,q);
part(A,q+1,r);
merge(A,p,q,r);
}
}
merge(int A[],int p,int q,int r)
{
int n1=q-r+1,n2=r-q,L[n1+1],R[n2+1],i,j,k;
L[n1+1]=100000;
R[n2+1]=100000;
for (i=0;i<n1;i++)
L[i]=A[p-1+i];
for (j=0;j<n2;j++)
R[j]=A[q+j];
i=0;j=0;
for (k=0;k<r;k++)
if(L[i]<=R[j])
{
A[k]=L[i];
i++;
}
else
{
A[k]=R[j];
j++;
}
}
Here is your corrected code:
#include<stdio.h>
#include<limits.h>
void merge(int A[],int p,int q,int r);
void part(int A[],int p,int r);
int main()
{
int A [6]={10,5,4,0,11,7}, n,y,z;
y=0; z=6;
part(A,0,z-1); // Pass starting from 0 to Length - 1 of Array
for(n=0;n<z;n++)
printf("%d\n", A[n]);
return 0;
}
void part(int A[],int p,int r)
{
if (p<r)
{
int q=(p+r)/2;
part(A,p,q);
part(A,q+1,r);
merge(A,p,q,r);
}
}
void merge(int A[],int p,int q,int r)
{
int n1=q-p+1,n2=r-q;
int L[n1+1],R[n2+1],i,j,k;
L[n1]=INT_MAX;
R[n2]=INT_MAX;
for (i=0;i<n1;i++)
L[i]=A[p+i];
for (j=0;j<n2;j++)
R[j]=A[q+j+1];
i=0;j=0;
for (k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
A[k]=L[i];
i++;
}
else
{
A[k]=R[j];
j++;
}
}
}
These are the parts which were wrong:
int n1=q-r+1,n2=r-q // --> Your calculation of new indices was wrong
These indices take you out of bounds of the array:
L[n1+1]=100000;
R[n2+1]=100000;
Also instead of using a random value like 100000 use INT_MAX in limits.h for the sentinel element.
for (k=0;k<r;k++) // ->wrong
You should move from left index of array to right not from 0th index.
Output:
0
4
5
7
10
11
Rest you can check for yourself.
Alternative solution with part parameters 0 to size of array. My old C compiler doesn't support variable sized arrays so I used _alloca() as a substitute. Other alternatives would be to pass a second array to be used as a temp array for the merge sort, and either a top down or bottom up merge sort. The copy operations can be avoided in top down by alternating the direction of the merge based on the level of recursion, with a pair of co-recursive functions: the top level would be partAtoA(), which would call partAtoB() (which would call partAtoA(), ...).
#include <stddef.h>
#include <stdio.h>
void merge(int A[],int p,int q,int r);
void part(int A[],int p,int r);
int main()
{
int A[6]={10,5,4,0,11,7}, n,y,z;
y=0;
z=sizeof(A)/sizeof(int);
part(A,y,z);
for(n=0;n<z;n++)
printf("%d\n", A[n]);
return 0;
}
void part(int A[], int p, int r)
{
int q;
if ((r - p) < 2)
return;
q=(p+r)/2;
part(A,p,q);
part(A,q,r);
merge(A,p,q,r);
}
void merge(int A[],int p,int q,int r)
{
int n1=q-p, n2=r-q;
int i,j,k;
/* using _alloca for variable size arrays */
int * L = _alloca(n1*sizeof(int));
int * R = _alloca(n2*sizeof(int));
for (i=0; i<n1; i++)
L[i]=A[p+i];
for (j=0; j<n2; j++)
R[j]=A[q+j];
i=0;j=0;
for(k=p;k<r;k++)
if(j>=n2 || i<n1 && L[i]<=R[j])
A[k]=L[i++];
else
A[k]=R[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);
}
}

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

Resources