首页 > 解决方案 > 单循环排序的复杂性

问题描述

function sortArrays(arr)
{
 // Sorting using a single loop
 for (let j = 0; j < arr.length - 1; j++) {

 // Checking the condition for two
 // simultaneous elements of the array
 if (arr[j] > arr[j + 1]) {
   
 // Swapping the elements.
 let temp = arr[j];
 arr[j] = arr[j + 1];
 arr[j + 1] = temp;
   
 // updating the value of j = -1
 // so after getting updated for j++
 // in the loop it becomes 0 and
 // the loop begins from the start.
 j = -1;
 }
}
 
return arr;
} 

我对这部分感到困惑,这个循环的复杂性是什么。只有当条件为真时,循环才会被反转。所以我认为复杂性介于 O(n) 和 O'Log(n) 之间。

标签: arraysloopssortingfor-looptime-complexity

解决方案


推荐阅读