Algorithm for finding the maximum difference in an array of numbers

后端 未结 7 484
夕颜
夕颜 2021-02-04 03:57

I have an array of a few million numbers.

double* const data = new double (3600000);

I need to iterate through the array and find the range (th

7条回答
  •  一生所求
    2021-02-04 04:25

    1. read in the first 1000 numbers.
    2. create a 1000 element linked list which tracks the current 1000 number.
    3. create a 1000 element array of pointers to linked list nodes, 1-1 mapping.
    4. sort the pointer array based on linked list node's values. This will rearrange the array but keep the linked list intact.
    5. you can now calculate the range for the first 1000 numbers by examining the first and last element of the pointer array.
    6. remove the first inserted element, which is either the head or the tail depending on how you made your linked list. Using the node's value perform a binary search on the pointer array to find the to-be-removed node's pointer, and shift the array one over to remove it.
    7. add the 1001th element to the linked list, and insert a pointer to it in the correct position in the array, by performing one step of an insertion sort. This will keep the array sorted.
    8. now you have the min. and max. value of the numbers between 1 and 1001, and can calculate the range using the first and last element of the pointer array.
    9. it should now be obvious what you need to do for the rest of the array.

    The algorithm should be O(n) since the delete and insertion is bounded by log(1e3) and everything else takes constant time.

提交回复
热议问题