We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Running Time of Algorithms
Running Time of Algorithms
+ 0 comments Python 3
def runningTime(arr): counter = 0 for i in range(1, len(arr)): for j in range(i-1, -1, -1): if arr[i] >= arr[j]: arr.insert(j+1, arr.pop(i)) counter += i - (j+1) break elif arr[i] < arr[j] and j==0: arr.insert(j, arr.pop(i)) counter += i-j return counter
+ 0 comments My Python3 Solution:
def runningTime(arr): # Write your code here newArr = arr; shifts = 0 for index in range(1, len(arr)): count = index while newArr[count] < newArr[count - 1] and count <= len(arr) - 1 and count > 0: v1 = newArr[count] newArr[count] = newArr[count - 1] newArr[count - 1] = v1 count -= 1 shifts +=1 return shifts
+ 0 comments C solution
int shifts = 0; for(int i = 1 ; i < arr_count ; i++){ int index = i; while(index){ if(arr[index] < arr[index-1]){ int temp = arr[index]; arr[index] = arr[index-1]; arr[index-1] = temp; shifts++; index--; } else break; } } return shifts;
+ 0 comments Modern C++ solution, using iterators:
int runningTime(vector<int> arr) { int res = 0; for(auto it1 = arr.begin() + 1; it1 != arr.end(); it1++){ for(auto it2 = make_reverse_iterator(it1) - 1; it2 != arr.rend(); it2++){ if(*(it2 + 1) > *(it2)){ int temp = *(it2); *(it2) = *(it2 + 1); *(it2 + 1) = temp; res++; } } } return res; }
+ 1 comment Here is my solution in java, javascript, python, C, C++, Csharp HackerRank Running Time of Algorithms Solution
Load more conversations
Sort 242 Discussions, By:
Please Login in order to post a comment