sort

void bubble(int arr[], int len)
{
for (int i = 0 ;i < len ;i++)
{
for (int j = 0 ;j < len - i - 1 ;j++)
{
if (arr[j] > arr[j+1])
{
int tmp = arr[j] ;
arr[j] = arr[j+1] ;
arr[j+1] = tmp ;
}//if
}//for j
}//for i
}

void insert(int arr[], int len)
{
for (int i = 1 ;i < len ;i++)
{
int tmp = arr[i] ;
int j = i-1 ;
while (0 <= j && arr[j] > tmp)
{
arr[j+1] = arr[j] ;
j-- ;
}

arr[j+1] = tmp ;
}
}

void select(int arr[], int len)
{
for (int i = 0 ;i < len-1 ;i++)
{
int j = 0 ;
int arr_min = i ;
for (j = i ;j < len ;j++)
{
if (arr[arr_min] > arr[j])
{
arr_min = j ;
}
}

int tmp = arr[i] ;
arr[i] = arr[arr_min] ;
arr[arr_min] = tmp ;
}
}

int fast_patition(int arr[], int l, int r)
{
int i = l-1, j = l ;
while (j < r-1)
{
if (arr[j] < arr[r-1])
{
i++ ;
int tmp = arr[i] ;
arr[i] = arr[j] ;
arr[j] = tmp ;
}

j++ ;
}

int tmp = arr[j] ;
arr[j] = arr[i+1] ;
arr[i+1] = tmp ;

return i+1 ;
}

void fast(int arr[], int l, int r)
{
if (l == r)
{
return ;
}
else
{
int m = fast_patition(arr, l, r) ;
fast(arr, l, m) ;
fast(arr, m+1, r) ;
}
}

#define P(x) ((x) / 2)
#define L(x) ((x) * 2)
#define R(x) ((x) * 2 + 1)

void heapify(int arr[], int cur, int len)
{
int l = L(cur) ;
int r = R(cur) ;
int largest = cur ;

if (l < len && arr[largest] < arr[l])
{
largest = l ;
}
if (r < len && arr[largest] < arr[r])
{
largest = r ;
}

if (cur != largest)
{
int tmp = arr[cur] ;
arr[cur] = arr[largest] ;
arr[largest] = tmp ;

heapify(arr, largest, len) ;
}
}

void build_heap(int arr[], int len)
{
for (int i = 0 ;i < P(len-1) ;i++)
{
heapify(arr, P(len) - i, len) ;
}
}

void heap(int arr[], int len)
{
for (int i = 0 ;i < len-1 ;i++)
{
int tmp = arr[len - i - 1] ;
arr[len - i - 1] = arr[1] ;
arr[1] = tmp ;

heapify(arr, 1, len-i-1) ;
}
}
posted @ 2011-10-20 23:22  walfud  阅读(265)  评论(0编辑  收藏  举报