Quick sort int array - C Data Structure

C examples for Data Structure:Sort

Description

Quick sort int array

Demo Code

#include <stdio.h>

void quicksort2(int[], int, int);

void swap(int[], int, int);

int main() {// www.  j a v a  2  s.  com

   int num[] = {10, 153, 112, 918, 163, 118, 312, 810, 416, 172, 121};
   int n = 10;
   quicksort2(num, 1, n);
   for (int h = 1; h <= n; h++) 
      printf("%d ", num[h]);

}
//sorts A[lo] to A[hi] in ascending order
void quicksort2(int A[], int lo, int hi) {
   int partition2(int[], int, int);
   if (lo < hi) {
      int dp = partition2(A, lo, hi);
      quicksort2(A, lo, dp);
      quicksort2(A, dp+1, hi);
   }
}

//return dp such that A[lo..dp] <= A[dp+1..hi]
int partition2(int A[], int lo, int hi) {
   
   int pivot = A[lo];
   --lo; 
   ++hi;
   
   while (lo < hi) {
      do --hi; while (A[hi] > pivot);
      do ++lo; while (A[lo] < pivot);
      if (lo < hi) swap(A, lo, hi);
   }
   return hi;
}

void swap(int list[], int i, int j) {
   int hold = list[i];
   list[i] = list[j];
   list[j] = hold;
}

Related Tutorials