奇怪的排序
忘记更新tmp了
C源码
//selection prolem O(N) and its test program
//select the Kth large
#include<stdio.h>
#include<stdlib.h>
#define N 10
#define K 3
int Select(int*a);
void BubbleSort(int* array, int n);
int* GeneArray();
int main(){
int* array = GeneArray();
int k = Select(array);
int i;
BubbleSort(array, N);
for(i = 0; i < N; i++)
{
printf("%d ", array[i]);
}
printf("\n%d", k);
return 0;
}
int Select(int*a)
{
int*arr = (int*)malloc(K*sizeof(int));//malloc space to arr
int end = K - 1;
// int flag = 0;//to judge whether the new one is inserted 0-no 1-yes
int tmp;//to store the present inserted number
int i;
for(i = 0; i < K; i++)//select K elements out of a
{
arr[i] = a[i];
}
tmp = a[K];//the first inserted one is a[K]
BubbleSort(arr, K);//sort the arr in increasing order
for(i = K; i < N; i++)
{
tmp = a[i];//inserted an element start from a[K]
end = K - 1;//the "invisibal" boundary of sorted array is equal to the number of rounds
while(end >= 0)
{
//I ignore the case that there are same numbers
if(tmp < arr[end])//if the insert one is smaller than the biggest sorted element
{
// flag = 1;
if(end == K - 1);//special treat goes to the last element of arr
else
arr[end + 1] = arr[end];//insert sort
end--;
}
else
break;
}
// if(flag)
if(end < K - 1)
arr[end + 1] = tmp;//there are two cases that the program runs here:
// flag = 0; //1. end is below 0, the new one is attached to the front of the sorted array
//2. the value of tmp is between arr[0] and arr[end]
}
return arr[K - 1];
}
void BubbleSort(int* array, int n)
{
int isSorted = 1;//to decide wether the array is ordered
int SortedIndex = n - 1;//to record the left sorted index
int i,j;
int temp;
int thisIndex;
for(i = 0; i < n; i++)//control the loop times
{
isSorted = 1;//initialize the state
for(j = 0; j < SortedIndex; j++)//SortedIndex is the right boundary of sorted elements
//which can spare you of a lot trouble of sorting ordered array
{
if(array[j] > array[j + 1])
{
isSorted = 0;//the array is not in order yet
temp = array[j];//exchange the order
array[j] = array[j + 1];
array[j + 1] = temp;
thisIndex = j;
}
}
if(isSorted)
break; //if the array is already in order, then stop the loop
SortedIndex = thisIndex;//renew the right boundary of sorted elements
}
}
int* GeneArray()
{
srand((unsigned int)time(0));//initialize the seed
int i;
int*array = (int*)malloc(sizeof(int)*N);
for(i = 0; i < N; i++)
{
array[i] = rand()%200 - 100;//to generate random number from -100 to 100
}
return array;
}