find kth largest number in an array

在一个数组中,找出第K打的数,原本以为很简单,但是就是这么个小东西,我写了半天,唉.....好丢人阿. 大家多多指教哈.....


思想是:给定的数组中,先对前K个元素进行排序,我用的是最最简单的bubble sort,然后从第K+1个元素开始,逐个和第K个元素进行比较,如果比K个元素小就不用考虑了,如果比第K个元素大,就要想办法插入进前K个元素序列中,在插入的过程中,还需要从原有的K序列中,弹出元素。这个弹出的元素,用不着了,不用关心它应该在什么位置了。



#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define ARRAY_SIZE 10

typedef int Status;


Status Find_Kth_Largest(int array[], int k)
{
    //sort the first k numbers
    BubbleSort(array, k);

    //after bubble sort, check the sequence
    printf("After bubble_sort\n");
    PrintArray(array);    
    
    //compare and merge the rest numbers one by one, compare begin with (k+1)th
    //we may bumping out one of the first k numbers
    Compare(array, k);
    printf("\n\n");
    PrintArray(array);
}

//compare and merge elements into the first k elements
//reminder: the array's index is stat from 0,so array[k]
//stand for the (k+1)th element
Status Compare(int array[], int k)
{
    int comPareStartPos = k;
    //int i;
    for(comPareStartPos ; comPareStartPos < ARRAY_SIZE ; comPareStartPos++){
 	//need merge and bumping out one of the first k elements
	if(array[k-1] < array[comPareStartPos]){
 	    printf("comPareStartPos is %d ", comPareStartPos);
	    InsertToArray(array, k, array[comPareStartPos]);					
	}
    }
    return 1;
}
//use bubble sort
Status BubbleSort(int array[], int k)
{
    int temp;
    int i, j;
    for(i = 0 ; i < k ; i++){
	for(j = i+1 ; j < k ; j++){
	    if(array[i] < array[j]){
		temp = array[i];
    		array[i] = array[j];
   		array[j] = temp;
	    }
    	}
    }
    return 1;
    
}

//insert into array and keep first k elements orderly
Status InsertToArray(int array[], int k, int elem)
{
    int i, j;
    //find the pos insert the elem
    for(i = 0 ; array[i] >= elem && i < k ; i++)
		;
	
    printf("The insert pos is %d ", i);    

    for(j = i ; j < k ; j++){
	array[j] = array[j+1];
	array[i] = elem;
    }
}


Status ArrayInit(int *array)
{   
    assert(array);
    int i;
    for(i = 0 ; i < ARRAY_SIZE ; i++){
	array[i] = (rand()%10);
    }	
    return 1;
}

void PrintArray(int array[])
{
    int i;
    for(i = 0 ; i < ARRAY_SIZE ; i++){
	printf("%d---", array[i]);
    }
}

void main()
{   
    int array[ARRAY_SIZE];
    //alloc memory
    if(array == NULL){
	exit(1);
    }
    ArrayInit(array);
    PrintArray(array);
    
    int k;
    printf("Input the Kth largest number you want find out ? k = \n");
    scanf("%d", &k);
    Find_Kth_Largest(array, k);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章