拍个QuickSort
-
void Swap(int *a, int *b)
-
{
-
int tmp = *a;
-
*a = *b;
-
*b = tmp;
-
}
-
-
int partition(int *a, int p, int r)
-
{
-
int x = a[r];
-
int i = p - 1;
-
int j = p;
-
-
for (; j <= (r - 1); j++)
-
if (a[j] < x)
-
{
-
i++;
-
Swap(&a[i], &a[j]);
-
}
-
Swap(&a[i+1], &a[r]);
-
return i+1;
-
}
-
-
-
void quickSort(int *a, int p, int r)
-
{
-
if (p < r) {
-
int q = partition(a, p, r);
-
quickSort(a, p, q - 1);
-
quickSort(a, q + 1, r);
-
}
-
}
-
int main(int argc, char *argv[])
-
{
-
int a[] = {0, 8, 7, 1, 3, 5, 6, 4};
-
int sorted[8] = {0,1,3,4,5,6,7,8};
-
int ii = 0;
-
-
quickSort(a, 2, 7);
-
for(; ii < 8; ii++)
-
//if(sorted[ii] != a[ii])
-
-
// printf("Success\n");
-
-
// int k1 = 3, k2 = 4;
-
// int a[2] ={0,1};
-
-
-
/* Swap(&a[0], &a[1]); */
-
/* printf("k1=%d, k2=%d", a[0], a[1]); */
-
-
return 0;
-
}
-
-
在阿里巴巴吃到的蜇
#include <stdio.h>
int printer(int x)
{
int counter = 0;
while(x) {
counter++;
x = x & (x-1);//算一的个数
}
return counter;
}
int main()
{
printf("%d\n", printer(9999));
return 0;
}
{
int counter = 0;
while(x) {
counter++;
x = x & (x-1);//算一的个数
}
return counter;
}
int main()
{
printf("%d\n", printer(9999));
return 0;
}
Fast median search
-
#define ELEM_SWAP(a, b) {
-
register elem_type t = (a); (a) = (b); (b) = (t);
-
}
-
-
elem_type quickSelect(elem_type arr[], int n)
-
{
-
int low, high;
-
int median;
-
int middle, ll, hh;
-
-
low = 0;
-
high = n - 1;
-
median = (low + high) / 2;
-
for (; ;)
-
{
-
if (high < low) /* one element only */
-
return arr[median];
-
if (high == low + 1) {
-
/* Two elements only */
-
if (arr[low] > arr[high])
-
ELEM_SWAP(arr[low], arr[high]);
-
return arr[median];
-
}
-
-
/* Find median of low, median and high items; Swap into positin low */
-
middle = (low + high) / 2;
-
if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]);
-
if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]);
-
if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]);
-
-
/* Swap low item (now in position middle) into low + 1 */
-
ELEM_SWAP(arr[middle], arr[low+1]);
-
-
/* Nibble from each end towards middle, swapping items was stuck */
-
ll = low + 1;
-
hh = high;
-
for (;;)
-
{
-
do ll++; while (arr[low] > arr[ll]);
-
do hh--; while (arr[hh] > arr[low]);
-
-
if (hh < ll) break;
-
ELEM_SWAP(arr[ll], arr[hh]);
-
-
}
-
/* Swap middle item (in position low) back into position */
-
ELEM_SWAP(arr[low], arr[hh]);
-
/* Re-set actieve partition */
-
if (hh <= median)
-
low = ll;
-
if (hh >= median)
-
high = hh - 1;
-
}
-
}
-
-