[英]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.给定一个由 n 个整数组成的未排序数组 𝐴 和一个整数 x,重新排列 𝐴 中的元素,使得所有小于或等于 x 的元素排在任何大于 x 的元素之前。
Note : Don't have to include integer x in the new array.注意:不必在新数组中包含整数 x。
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.要尝试此操作,您首先需要了解排序算法、Big O 表示法,然后查看哪种排序算法最适合所提出的问题。
1) Given your problems defines that some values come before a set point, and some after, a merge sort would be best here. 1)鉴于您的问题定义了一些值在设置点之前,有些值在设置点之后,合并排序在这里最好。 See this .
看到这个。
2) Have a read about Big O notation, and time complexity of certain sorting algorithms. 2) 阅读有关 Big O 表示法和某些排序算法的时间复杂度的信息。 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:第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:第2部分:
The above algorithm would have a time complexity of O(n)
, where n
is the number of elements in the listToSort
.上述算法的时间复杂度为
O(n)
,其中n
是listToSort
中元素的listToSort
。 Best case would be O(1)
, where there is 1 element, and worst case is O(n)
最好的情况是
O(1)
,其中有 1 个元素,最坏的情况是O(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.