简体   繁体   中英

Given an unsorted array 𝐴 of n integers and an integer x, rearrange the elements in 𝐴

Given an unsorted array 𝐴 of n integers and an integer x, rearrange the elements in 𝐴 such that all elements less than or equal to x come before any elements larger than x.

Note : Don't have to include integer x in the new array.

What is the running time complexity of your algorithm? Explain your answer.

To attempt this, you first need to understand sorting algorithms, Big O notation, then see which sorting algorithm best fits the question asked.

1) Given your problems defines that some values come before a set point, and some after, a merge sort would be best here. See this .

2) Have a read about Big O notation, and time complexity of certain sorting algorithms. There is always a best case and worst case. You can also calculate the complexity of any algorithm you design using this notation. See below.

Calculating complexity of an algorithm

EDIT: To help, here is a solution.

Part 1:

function sortHalf(List listToSort, value x):
    List firstHalf;
    List secondHalf;
    for (Integer i in listToSort):
        if i less than x then firstHalf.add(i);
        else if i greater than x then secondHalf.add(i);
    loop
    List finalList;
    finalList.addAll(firstHalf);
    finalList.addAll(secondHalf);
    return finalList;
end

Part 2:

The above algorithm would have a time complexity of O(n) , where n is the number of elements in the listToSort . Best case would be O(1) , where there is 1 element, and worst case is O(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM