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);

}

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