Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created October 13, 2015 09:09
Show Gist options
  • Select an option

  • Save davepkennedy/2f21392926bb7935aaa0 to your computer and use it in GitHub Desktop.

Select an option

Save davepkennedy/2f21392926bb7935aaa0 to your computer and use it in GitHub Desktop.
Sorting and searching in C. Slightly meh recursion in maxHeap…
#include <stdio.h>
#define LEFT(x) (2*(x)+1)
#define RIGHT(x) (2*(x)+2)
#define PARENT(x) (((x)-1)/2)
void swap (int* a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
void maxHeap (int* a, int i, size_t size)
{
int l = LEFT(i);
int r = RIGHT(i);
int m = -1;
m = (l < size && a[l] > a[i]) ? l : i;
m = (r < size && a[r] > a[m]) ? r : m;
if (m != i) {
swap(a, i, m);
maxHeap(a, m, size);
}
}
void buildMaxHeap (int* array, size_t size)
{
int hs = size / 2;
for (int i = hs; i > 0; i--) {
maxHeap(array, hs - i, size);
}
}
void heapSort (int* array, size_t size) {
buildMaxHeap(array, size);
for (int i = size - 1; i >= 0; i--) {
swap(array, 0, i);
maxHeap(array, 0, i);
}
}
int find (int elem, int* array, size_t size) {
int pos = -1;
int low = 0;
int high = size - 1;
while (low < high) {
int mid = low + ((high - low) / 2);
if (array[mid] < elem) {
low = mid;
} else if (array[mid] > elem) {
high = mid;
} else {
pos = mid;
break;
}
}
return pos;
}
int main(int argc, const char * argv[]) {
// insert code here...
int numbers [] = {1,9,2,8,3,7,4,6,5};
heapSort(numbers, 9);
int pos = find (7, numbers, 9);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment