filling 2d array with mutiplicatio table - c

#include<stdio.h>
#include<stdlib.h>
int** createMatrix(int n)
{
int i, a, **tab,x;
tab=(int**)malloc(n*sizeof(int*));
if(tab==0)
{
return NULL;
free(tab);
}
for(i=0;i<n;i++)
{
tab[i]=(int*)malloc(n*sizeof(int));
if(tab[i]==NULL)
{
for(x=0;x<i;x++)
{
free(tab[x]);
}
free(tab[i]);
return NULL;
}
}
}
void fillMatrix(int*** tab, int n)
{
int i, a;
for(i=0;i<n;i++)
{
for(a=0;a<n;a++)
{
*tab[i][a]=(a*i);
}
}
}
int main()
{
int roz, **tab,i,x;
printf("size of the array: \n");
scanf("%d",&roz);
tab=createMatrix(roz);
if(tab==NULL)
{
printf("error");
return -1;
}
fillMatrix(&tab, roz);
for(i=0;i<roz;i++)
{
printf("\n");
for(x=0;x<roz;x++)
printf("%d",tab[i][x]);
}
return 0;
}
Hi! I need to write a program that makes 2d arrays and I want to fill them with multiplication table. Program compiles without single warning or error, but after puttintan input it crashes. And by the way, could you tell me why I have to put 3x* in fillMatrix?

int** createMatrix(int n)
You should be returning the double pointer from the function which I see you are not doing.
int** createMatrix(int n)
{
int i, a, **tab,x;
tab=(int**)malloc(n*sizeof(int*));
// Do your allocations and other stuff
return tab;
}
Take care of accessing the elements using triple pointer. Like
(*tab)[i][a] = (a*i);
You can get the job done using doule pointers itself.

You have several problems
Pointeless free(tab) in your createMatrix() function, it's after the return statement, it will never be executed.
You free the tab[i] element which is NULL in createMatrix() inside the loop where you malloc the pointers of the array.
What you should do is
free(tab);
instead.
You never return the malloced tab.
Your fillMatrix() function is unecessarily taking a int *** triple pointer, you don't need that, if you pass the pointer you directly modify the data.
You have an operator precedence issue in fillMatrix()
*tab[i][a] = (a*i);
this doesn't mean what you think, first [] is applied, and then you dereference it with * which is equivalent to
*(tab[i][a]) = (a * i); -> *(tab[i][a]) -> tab[i][a][0]
what you want is
(*tab)[i][a] = a * i;
You don't free the pointers after printing them.
This is your code with all this issues fixed.
#include <stdio.h>
#include <stdlib.h>
int **createMatrix(int n)
{
int i, **tab, x;
tab = malloc(n*sizeof(int*));
if (tab == 0)
return NULL;
for (i = 0 ; i < n ; i++)
{
tab[i] = malloc(n * sizeof(int));
if (tab[i] == NULL)
{
for (x = 0 ; x < i ; x++)
free(tab[x]);
free(tab);
return NULL;
}
}
return tab;
}
void fillMatrix(int **tab, int n)
{
int i, a;
for (i = 0 ; i < n ; i++)
{
for (a = 0 ; a < n ; a++)
{
tab[i][a] = (a*i);
}
}
}
int main()
{
int roz, **tab, i, x;
printf("size of the array: \n");
scanf("%d", &roz);
tab = createMatrix(roz);
if (tab == NULL)
{
printf("error");
return -1;
}
fillMatrix(tab, roz);
for (i = 0 ; i < roz ; i++)
{
printf("\n");
for (x = 0 ; x < roz ; x++)
printf("%4d ", tab[i][x]);
printf("\n");
free(tab[i]);
}
free(tab);
return 0;
}

And by the way, could you tell me why I have to put *** in fillMatrix?
That is an excellent question. Incidentally, it provides the key to answering the "why does my program crash" question. The reason the program crashes is that you are using the matrix incorrectly: you treat it like a 2D array of pointers, rather than a pointer to a 2D array. If you add parentheses, your program would stop crashing:
(*tab)[i][a]=(a*i);
Better yet, change the program to take ** that it needs:
void fillMatrix(int** tab, int n) {
...
tab[i][a]=(a*i); // <<== No asterisk
}
...
fillMatrix(tab, roz); // <<== No ampersand
Note: when you compile your program, you should see the "control reaches the end of non-void function without returning a value". This is because you forgot to add return tab at the end of the function that creates your matrix.
Demo.

You asked:
And by the way, could you tell me why I have to put 3x* in fillMatrix?
That is not necessary. You could use:
void fillMatrix(int** tab, int n)
{
int i, a;
for(i=0;i<n;i++)
{
for(a=0;a<n;a++)
{
tab[i][a]=(a*i);
}
}
}

Related

C, Segmentation fault while using dynamic array in struct

I'm trying to add new element to dynamic array in C (I know that I must free all memory. I will do it later), but I get this error every time:
But, what is strange, if I compile from terminal, like that, code works properly.
So, where is the error and how i can beat it?
Thank you!
All my code:
main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct vector
{
int size;
int *array;
int alreadyIn;
}vector;
vector *vectorInit(int size)
{
vector *newVec = (vector *)malloc(sizeof(vector));
if(!newVec){printf("No memory!\n"); return NULL;}
newVec->size = size;
newVec->array = (int *)malloc(size * sizeof(int));
return newVec;
}
void allocNewMemory(vector *vect, int howMuch)
{
vect->array = (int *)realloc(vect->array ,(vect->size + howMuch) * sizeof(int));
vect->size += howMuch;
}
void pushBack(vector *vect, int number)
{
int howMuch = 5;
if(vect && vect->alreadyIn < vect->size)
{
vect->array[vect->alreadyIn] = number;
vect->alreadyIn++;
}
else
{
printf("Alloc new memory for %d elements...\n", howMuch);
allocNewMemory(vect, howMuch);
pushBack(vect, number);
}
}
void printVector(vector *vect)
{
for (int i = 0; i < vect->alreadyIn; i++)
{
printf("%d ", vect->array[i]);
}
printf("\n");
}
int main()
{
int startSize = 4;
vector * vec = vectorInit(startSize);
for (int i = 0; i < 6; i++)
{
pushBack(vec, i+1);
}
printVector(vec);
return 0;
}
You never initialize the alreadyIn member in the structure. That means its value will be indeterminate (and seemingly garbage or random).
You need to explicitly initialize it to zero:
vector *vectorInit(int size)
{
vector *newVec = malloc(sizeof(vector));
if(!newVec)
{
printf("No memory!\n");
return NULL;
}
newVec->size = size;
newVec->array = malloc(size * sizeof(int));
newVec->alreadyIn = 0; // Remember to set this to zero
return newVec;
}
This problem should have been easy to detect in the debugger.
Also note that I removed the casts from malloc. One should not cast the result of malloc, or really any function returning void *.

Array Rotation with Getting Max Value and Index Location of Array C language

I'm creating a program that gets the index value of the highest element in an array.
Sample Input:
4 (Size of a[])
1 2 4 3 (Elements of a[])
2 (Size of rotate[])
0 2 (Elemnts of rotate[])
Output will be:
2
0
Using left rotation.
In the First Rotation (0) the location will be 2 because 4 is the highest a[1,2,4,3]
In the Second Rotation (2) the location will be 0 because 4 is the highest a[4,3,1,2]
Problem is i'm not getting the desired output and there was a warning in for(j=0;j<rotateValue;j++)
I want the function to be as it is and to fix this part to int* output = getMaxIndex(a,rotate);
but i don't know how.
Thank you in advance for helping!
#include<stdio.h>
int i,j,k; // for looping
int n, m; // sizes of arrays
int getMaxIndex(int* a[], int* rotate[])
{
int indices[m];
for(i=0;i<m;i++)
{
int* rotateValue = rotate[i];
for(j=0;j<rotateValue;j++) // for rotation
{
int* first = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
}
a[n-1] = first;
}
int location;
int* max = a[0];
for(j=0;j<n;j++) // getting the max element
{
if(a[j] > max)
{
max = a[j];
// printf("Max added");
}
}
for(j=0;j<n;j++) // getting the location
{
if(max == a[j])
{
location = j;
// printf("Loc added");
}
}
indices[i] = location;
}
// for(i=0;i<m;i++) // printing here to know if correct
// {
// printf("%d",indices[i]);
// }
return *indices;
}
int main()
{
scanf("%d",&n); // inputting array size
int* a[n];
for(i=0;i<n;i++) // filling elements of a[]
{
scanf("%d",&a[i]);
}
scanf("%d",&m); // inputting rotate array size
int* rotate[m];
for(i=0;i<m;i++) // filling elements of rotate[]
{
scanf("%d",&rotate[i]);
}
int* output = getMaxIndex(a,rotate); // call function
for(i=0;i<m;i++) // printing output
{
printf("%d",output[i]);
}
}
int getMaxIndex(int* a[], int* rotate[]);
Designing getMaxIndex() in the following way should solve most of the issues:
int* getMaxIndex(int a[], int rotate[])
{
static int indices[MAX_POSSIBLE_VALUE_OF_M];
/*
your code
*/
return indices;
}
Now, all you have to do is adjust your code in the main() function accordingly.
Why declare the array indices[] in getMaxIndex() as static int?
indices[] is a local variable of getMaxIndex(). And so after the return statement of getMaxIndex() is executed, it shall be destroyed. That means, if you return indices[] to main(), the main function will not be able to access indices[] anymore. And this issue can be solved by declaring indices[] as a static int instead of int.
NOTE: static array should have constant size. So, its size should be declared as maximum possible value of m instead of m.
Required adjustments in main():
Declare a[] and rotate[] as int instead of int*.
Check out my code.I am getting the correct output. I have written down a few mistakes that you have made.
void getMaxIndex(); //function declaration
int n, m; //for storing array size
int * a, * rotate;
int main(void) {
int i; //to use in loops
scanf("%d", & n); // inputting array size
a = (int * ) malloc(n * sizeof(int));
for (i = 0; i < n; i++) // filling elements of a[]
{
scanf("%d", & a[i]);
}
scanf("%d", & m); // inputting rotate array size
rotate = (int * ) malloc(m * sizeof(int));
for (i = 0; i < m; i++) // filling elements of rotate[]
{
scanf("%d", & rotate[i]);
}
getMaxIndex();
free(a);
free(rotate);
return 0;
}
void getMaxIndex() {
int i;
int aMax, rotateMax;
int aMaxIndex, rotateMaxIndex;
aMax = a[0];
rotateMax = rotate[0];
for (i = 1; i < n; i++) {
if (aMax < a[i]) {
aMax = a[i];
aMaxIndex = i;
}
}
for (i = 1; i < m; i++) {
if (rotateMax < rotate[i]) {
rotateMax = rotate[i];
rotateMaxIndex = i;
}
}
printf("%d\n%d", aMaxIndex, rotateMaxIndex);
}
My suggestions:
Always try to allocate memory for your array dynamically so that you can avoid errors such as Segmentation Fault or Core Dump.
In your code you have used array of pointers instead of pointers, there you went wrong. Try refering to your textbook or other sources to get a clear idea regarding pointers.
For example, in your code you passed your array named indices using the line:
return indices;
Now, to pass a pointer you don't need to use asterisk(). Simply write: return indices;
Also, don't use asterisk symbol to declare an array.
Your Code:
int* a[n];
Here you are declaring an array of pointers not an array.
Correct code:
int a[n];
But I liked your logic. You just have to implement it with the correct syntax. Just keep practicing.
I the code which I've written is understood by you, my work here is done. Happy Coding!!!

Code Bug: Segmentation Fault [EVERYTIME]

I am writing this C/C++ program that is suppose to find the mean, median, and mode of a varied size array. Although, I keep getting a Segmentation Fault regardless of the input. What is wrong with my code? Any suggestions always appreciated! :)
Here is the code:
#include <stdio.h>
//#include <string.h>
//#include <math.h>
#include <stdlib.h>
Prototypes:
void sort(double*[],int);
static int min(double,double[],int);
double mean(double[],int);
double median(double[],int);
double mode(double[],int);
int numberOf(double,double[],int);
Main Function:
int main() {
int i;
scanf(" %d ",&i); //10
double arr[i]; //array that contains all the values and will be sortted
for (int j=0; j<i; j++) { //64630 11735 14216 99233 14470 4978 73429 38120 51135 67060
scanf(" %lf ",&arr[j]);
}
printf("%.1lf\n%.1lf\n%.0lf",mean(arr,i),median(arr,i),mode(arr,i));
return 0;
}
Sort Function:
The end result should update the array arr from the call in the Median Function. Changes the used values in the original array to -1 until that is the entire array.
void sort(double* arr[],int l) {
double arr2[l];
for (int i=0; i<l; i++) {
int j;
if (i)
j = min(arr2[i-1], *arr, l);
else
j = min(0, *arr, l);
arr2[i] = *arr[j];
*arr[j] = -1;
}
for (int i=0; i<l; i++) {
*arr[i] = arr2[i];
}
}
Min Function (helper function for the Sort Function):
Finds the minimum value amongst the array elements that is greater than or equal to minLookingTo
Returns the position the value is in.
static int min(double minLookingTo,double arr[],int l) {
int minP;
double minA = minLookingTo;
for (int i=0; i<l; i++) {
if (arr[i] == -1)
continue;
if (minLookingTo<=arr[i] && arr[i]<=minA) {
minP = i;
minA = arr[i];
}
}
return minP;
}
Mean Function:
Returns the mean of the inputted array with the length l
double mean(double arr[],int l){
double total = 0;
for (int i=0; i<l; i++) {
total += arr[i];
}
return total/l;
}
Median Function:
Uses the Sort Function. Assuming that works, returns the median.
double median(double arr[],int l){
sort(&arr,l);
double d = arr[(l/2)+1];
double dd = arr[(l/2)];
if (l%2!=0)
return d;
return (d+dd)/2;
}
Mode Function:
Uses the NumberOf Function to determine the array element with the maximum amount of repeats. Returns the lowest value of the highest (equal) repeats.
double mode(double arr[],int l){
int maxA;
int maxP;
for (int i=0;i<l;i++) {
int j = numberOf(arr[i],arr,l);
if (j>maxA) {
maxA = j;
maxP = i;
}
else if (j==maxA && arr[maxP]>arr[i])
maxP = i;
}
double d = arr[maxP];
return d;
}
NumberOf Function:
Helper function for the Mode Function. Returns the amount of elements with the looking value.
int numberOf(double looking,double arr[],int l) {
int amount = 0;
for (int i=0; i<l; i++)
if (looking == arr[i])
amount++;
return amount;
}
I tracked your segmentation fault to your sort() routine called by median(). Rather than fix sort(), I substituted qsort() from the library to convince myself that's the problem:
// Median Function:
// Uses the Sort Function. Assuming that works, returns the median.
int comparator(const void *p, const void *q) {
double a = *((double *) p);
double b = *((double *) q);
return (a > b) - (a < b); // compare idiom
}
double median(double array[], int length) {
// sort(array, length);
qsort(array, length, sizeof(double), &comparator);
double d = array[length / 2];
if (length % 2 != 0) {
return d;
}
double dd = array[(length / 2) - 1];
return (d + dd) / 2;
}
For the example list of numbers provided, after correcting the rest of the code, this returns a median of 44627.5
Other fixes:
You're missing a final newline here:
printf("%.1lf\n%.1lf\n%.0lf",mean(arr,i),median(arr,i),mode(arr,i));
You should probably initialize the variables in mode():
double mode(double array[], int length) {
int maxA = INT_MIN;
int maxP = -1;
for (int i = 0; i < length; i++) {
int j = numberOf(array[i], array, length);
if (j > maxA) {
maxA = j;
maxP = i;
} else if (j == maxA && array[maxP] > array[i]) {
maxP = i;
}
}
return array[maxP];
}
Your code has a series of errors. Some of them:
You don´t need (in this case) to use spaces in scanf. This is causing a reading error.
You don't need to pass an array address to a function in order to alter its values. Arrays are always passed by reference. So change your function from void sort(double*[],int); to void sort(double[],int);, make the necessary corrections inside the function and call it using sort(arr,l); instead of sort(&arr,l);
Your min() function declares an uninitialized variable minP, so this variable contains garbage from your memory. The for() loop isn't entering none of the both if() conditions, so your function ends and returns the still uninitialized variable minP. This random value is then used to access an index in your array: j = min(0, arr, l); min returns an random number and then arr2[i] = arr[j]; accessing forbidden memory region, which is causing your segmentation fault error. The same problem is occurring with the variables maxP and maxA in the mode() function.
You must always be careful when accessing your arrays to not go beyond its bounds and always be sure that variables will be initialized when using them. And as others have commented, I also highly recommend you to learn how to debug your programs, since this will help you to analyze its execution and trace bugs.

Using pointer to pointer to make a dynamic matrix of integers

I'm trying to make a dynamic matrix that is based on an integer pointer to pointer, this variable is allocated dynamically, but I'm having a little trouble using it, I don't know if I am using it wrong or something, but the outcome is not as expected. Is it something wrong that I'm doing or am I not thinking this through?
void pkn(int n, int k)
{
int chec = checagemInicial(n,k);
if(chec == 1)
{
return;
}
int mat[n];
int **resultado = NULL, **newMem;
int posicoes = 0;
initiateArray(mat, n);//initialize the matrix with one's
while(functionthatchecksthings1(mat, n, k) == 0)//this 2 function works no need to worry
{
if(functionthatchecksthings2(mat, n , k))
{//i think the problem might be or here
newMem = realloc(resultado, ((sizeof(int)*n)+(posicoes*sizeof(int)*n)));
if(newMem)
{//or here
resultado = newMem;
}
int i = 0;
for(i; i<n;i++)
{//or here but don't know where
resultado[posicoes][i] = mat[i];
}
posicoes++;
}
somaArray(mat, k, n-1);
}
//or in the very least case i'm printing it wrong
printaArray(resultado, n, posicoes);
system("pause");
free_matrix(posicoes, resultado);
}
This one is the function that prints the pointer, it might be wrong here too, but I seriously don't know.
void printaArray(int **ar, int n, int p)
{
int i = 0, j;
for(i; i < p; i++)
{
j = 0;
for(j; j < n; j++)
{
printf("%d ",(ar[i][j]));
}
printf("\n");
}
printf("%d\n", p);
}
I would like to thank everyone and I'm sorry if I haven't made myself clear, or if I've said something wrong/misspelled anything

C - Custom qsort not working

I am trying to make a qsort type of function that has the same paramenters. I also wrote 3 functions to compare int, float and characters. For some reason it does not work in any case.
I don't know whether this is a problem regarded my qsortx function or not, but I checked it several times and it should work perfectly fine. I am not sure what the problem is, or what I am doing wrong. I am currently learning the function pointers and I might not have got everything right related to it. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void qsortx(void*, int, int, int (*)(const void*, const void*));
int intcmp();
int floatcmp();
int charcmp();
int main()
{
int i,n;
char items[]={'c', 'a', 'b'};
n = 3;
for (i=0;i<n;++i) {
printf("%c ", items[i]);
}
printf("\n");
qsortx(items, n, sizeof(char), charcmp);
for (i=0;i<n;++i) {
printf("%c ", items[i]);
}
printf("\n");
return 0;
}
void qsortx (void *tp, int length, int pace, int(*fp)(const void* a, const void* b)) {
int switched,i,j;
void *p;
p=(void*)malloc(pace);
switched = 1;
while (1) {
if (switched == 0) {
return;
}
switched = 0;
for (i=0; i<length-1;++i) {
for (j=0;j<length-1;++j) {
printf("%c %c", tp+i, tp+j);
if (fp(tp+i, tp+j) > 0) {
memcpy(p, tp+i, pace);
memcpy(tp+i, tp+j, pace);
memcpy(tp+j, p, pace);
switched++;
}
}
}
}
}
int intcmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int floatcmp(const void* a, const void* b) {
return *(float*)a - *(float*)b;
}
int charcmp(const void* a, const void* b) {
return *(char*)a - *(char*)b;
}
You have multiple problems related to pointer arithmetic and element sizes. You also have a logic error in your sort (which I guess you know is a unidirectional shaker sort). Here's a version of the qsortx() function that fixes these deficiencies:
void qsortx (void *tp, int length, int pace, int(*fp)(const void* a, const void* b)) {
if (length > 1) {
char *bound = ((char *) tp) + (length * pace);
char *p = malloc(pace);
char *item1p;
for (item1p = tp; item1p < (bound - pace); item1p += pace) {
char *item2p;
for (item2p = item1p + pace; item2p < bound; item2p += pace) {
if (fp(item1p, item2p) > 0) {
memcpy(p, item1p, pace);
memcpy(item1p, item2p, pace);
memcpy(item2p, p, pace);
}
}
}
free(p);
}
}
Note that:
All pointer arithmetic is performed on values of type char *.
The element size (pace) must be taken into account as you step through the input array, else you just scramble your data.
The innermost loop should start at the element after the one being considered in the next-outer loop.
switched = 1 is a better choice than switched ++ because it cannot overflow, and all you care about is zero vs. non-zero. (Update: but switched is no longer relevant.)
(Update) It is incorrect to exit early in the event that a pass through the item1p loop results in zero swaps. Just because one element is already in its correct place does not mean that all the subsequent elements are also in their correct places. I updated my code above to remove that behavior.
(Update) As chux observed, the temporary space reserved for swapping elements was not freed. I added an appropriate free(p).
(Update) I also made sorting conditional on the array length being greater than 1, which avoids undefined behavior associated with bound - pace in the event that the length is zero.
here is the pseudo code and implementation of the quicksort (qsort) algorithm, with some accessory code, as defined in the http://www.codingbot.net/2013/01/quick-sort-algorithm-and-c-code.html web page:
Note that this algorithm is slightly different from qsort()
in that there is a different parameter list and certain other details.
However, the basic algorithm is the same.
function quicksort('array')
if length('array') ≤ 1
return 'array' // an array of zero or one elements is already sorted
select and remove a pivot value 'pivot' from 'array'
create empty lists 'less' and 'greater'
for each 'x' in 'array'
if 'x' ≤ 'pivot'
then append 'x' to 'less'
else
append 'x' to 'greater'
endif
end for
return concatenate(quicksort('less'), 'pivot', quicksort('greater') );
notice that qsort is a partition sort, using recursion.
#include<stdio.h>
#include<conio.h>
void quick_sort(int arr[20],int,int);
int main()
{
int arr[20],n,i;
clrscr();
printf("Enter the number of elements in the Array: ");
if( 1 != scanf(" %d",&n) )
{
perror( "scanf for count of elements" );
exit(1);
}
printf("\nEnter %d elements:\n\n",n);
for(i=0 ; i<n ; i++)
{
printf(" Array[%d] = ",i);
if( 1 != scanf(" %d",&arr[i]) )
{
perror( "scanf for element values" );
exit(2);
}
}
quick_sort(arr,0,n-1);
printf("\nThe Sorted Array is:\n\n");
for(i=0 ; i<n ; i++)
{
printf(" %4d",arr[i]);
}
getch();
}
void quick_sort(int arr[20],int low,int high)
{
int pivot; // used in partitioning the array
int j; // loop index
int temp; // for swapping
int i; // loop index
if(low<high)
{
pivot = low;
i = low;
j = high;
while(i<j)
{
// find next item not in proper sequence
while((arr[i] <= arr[pivot]) && (i<high))
{
i++;
}
// find next item not in proper sequence
while(arr[j] > arr[pivot])
{
j--;
}
// following is where a callback function would be invoked
if(i<j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
temp=arr[pivot];
arr[pivot] = arr[j];
arr[j]=temp;
// following is where recursion is used to perform sort on sub partitions
quick_sort(arr,low,j-1);
quick_sort(arr,j+1,high);
}
}
this is a much better algorithm for your purposes.
however, it only handles integers, so you would need to
add the comparison function as a 4th parameter to quicksort()
and modify the code to use your comparison function
#include <stdio.h>
#include <stdlib.h>
void swap(int *x,int *y);
int choose_pivot(int i,int j );
void quicksort(int list[],int m,int n);
void display(int list[],const int n);
int main()
{
const int SIZE = 10;
int list[SIZE];
int i = 0;
/* generates random numbers and fill the list */
for(i = 0; i < SIZE; i++ )
{
list[i] = rand();
}
printf("The list before sorting is:\n");
display(list,SIZE);
/* sort the list using quicksort algorithm */
quicksort(list,0,SIZE-1);
printf("The list after sorting:\n");
display(list,SIZE);
}
void swap(int *x,int *y)
{
// for integer swaps, 3 exclusive OR operations would be much faster
// and not require a temp variable
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int choose_pivot(int i,int j )
{
return((i+j) /2);
}
void quicksort(int list[],int m,int n)
{
int key,i,j,k;
if( m < n)
{
k = choose_pivot(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
{
i++;
}
while((j >= m) && (list[j] > key))
{
j--;
}
if( i < j)
{
swap(&list[i],&list[j]);
}
}
/* swap two elements */
swap(&list[m],&list[j]);
/* recursively sort the lesser list */
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
void display(int list[],const int n)
{
int i;
for(i=0; i<n; i++)
{
printf("%d\t",list[i]);
}
}

Resources