The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
22 views

Why the code is not showing correct sorting ?(here pivot is smaller index element, i.e. arr[low])

#include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
 
    void fillArray(int array[], int n)
    {
    	time_t t;
    	time(&t);//get current time
    	srand(t);//gives current time as seed for random number generator
 
 
    	for(int i = 0; i < n; i++)
    	{
    		array[i] = rand()%(10*n);//Doing mod to avoid very large numbers
    	}
    }
    void printArray(int array[], int n)
    {
    	for(int i = 0; i < n; i++)
    	{
    		printf("\n%d ", array[i]);
    	}
    }
    void swap(int *a, int *b)
    {
    	int temp = *a;
    	*a = *b;
    	*b = temp;
    }
int partition (int arr[], int low, int high)
{
	int j;
	static int swap1=0;
	static int swap2=0;
    int pivot = arr[low];    // pivot
    int i = (low);  // Index of smaller element
 
    for (j = low+1; j <= high; j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if (arr[j] <= pivot)
        {
            i++;    // increment index of smaller element
            swap(&arr[i], &arr[j]);
            swap1++;
        }
    }
    swap(&arr[i], &arr[low]);
    swap2++;
    printf("Total number of swaps:%d",(swap1+swap2));
    return (i + 1);
}
 void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);
 
        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}
 
    int main()
    {
    	int * array, n=5;
		int low=0;
 
 
    	//printf("Enter the no. of numbers: ");
    	//scanf("%d", &n);
    	array = malloc(n * sizeof(int));
    	fillArray(array, n);
        quickSort(array,low,n);
    	printArray(array, n);
    	return 0;
    }

 

asked in Programming by Veteran (100k points)
edited by | 22 views
0
I think there is some wrong in partition

but cannot found any
0
Check the partition function, it's implemented totally in a wrong way...
0
but my pivot is 1st one

it is not like as cormen, where it is last element
0
I am also saying according to you only mam.... First on the paper wrote it.. You will get where you did mistake

Please log in or register to answer this question.

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

42,458 questions
48,493 answers
154,720 comments
63,093 users