开发者

Dynamic Array in order printing

I need to print an array of in order of largest to smallest. For simplicity, we'll say that it is an array of ints.

The only way I can think to do it is loop through the array, find the largest element, print it and set a corresponding boolean fl开发者_Go百科ag so it doesn't get printed twice. Is there a better way to go about this?

int *array;

// Fill array, malloc, all that good stuff

int i, j, max = 0, max_index = 0;
int isPrinted[ARRAY_SIZE] = {0};

for (i = 0; i < ARRAY_SIZE; i++) {
  for (j = 0; j < ARRAY_SIZE; j++) {
    if (isPrinted[j] == 0 && array[j] > max) {
      max = array[j];
      max_index = j;
    }  
  }
  isPrinted[max_index] = 1;
  printf("%d", max);
  max = 0;
}


Yes..sort the array before printing and then print it. If you can't modify the original array, copy the elements to another inserting them in the correct order and print the second one.


Can't you sort the array and then print it ? Or copy the array, sort the copy and print it ? The complexity will be dramatically better (O(n log(n)) instead of O(n ** 2) with your algorithm).


Sort it, then print it. For integers it's possible to do this in linear time. With standard qsort it's O(n*log(n)).

// stdlib.h
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) ); 


I think you should preferably go for a sort algorithm that reorder your array the way you want. Then print the content of your array sequentially.


If you can change the order of the elements, you could use an sort-algorithm on your array before printing.


As others have pointed out, it's generally more efficient to sort the data first.

Rather than completely sorting the data, however, you can put the data into a priority queue, and print items as your remove them from the priority queue. Although it's not a huge difference (by any means), this does reduce work slightly compared to completely sorting the data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜