The Gateway to Computer Science Excellence
0 votes

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]);
    swap(&arr[i], &arr[low]);
    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);
    	printArray(array, n);
    	return 0;


in Programming by
edited by | 137 views
I think there is some wrong in partition

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

it is not like as cormen, where it is last element
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
52,345 questions
60,517 answers
95,368 users