You are viewing a single comment's thread. Return to all comments →
can anyone tell me what is wrong wirh this code ? when i am dry running for input 3 1 2 my code shoudl give correct output but its not idk why
void almostSorted(vector arr) { vector nums = arr; sort(nums.begin(), nums.end()); int swap = 0; int first = -1; int second; int start, ending; //3 1 2
for (int i = 0; i < arr.size(); i++) { if (nums[i] != arr[i]) { swap++; if (first == -1) { first = i + 1; } else { second = i + 1; } } if (swap == 2 && i == arr.size() - 1) { cout << "yes" << endl; cout << "swap " << first << " " << second; return; } } int len = arr.size(); int k = 0; // 3 1 2 if (swap > 2) { for (int i = 0; i < len;) { if (arr[i] == nums[i]) { i++; } if (arr[len - 1] == nums[len - 1]) { len--; k++; } else { reverse(arr.begin() + i, arr.end() - k); start = i; ending = len; } } for (int i = 0; i < arr.size(); i++) { if (arr[i] != nums[i]) { cout << "no"; return; } if (i == arr.size() - 1 && arr[i] == nums[i]) { cout << "yes" << endl << "reverse " << start + 1 << " " << ending; } } } else { cout << "no"; }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Almost Sorted
You are viewing a single comment's thread. Return to all comments →
can anyone tell me what is wrong wirh this code ? when i am dry running for input 3 1 2 my code shoudl give correct output but its not idk why
void almostSorted(vector arr) { vector nums = arr; sort(nums.begin(), nums.end()); int swap = 0; int first = -1; int second; int start, ending; //3 1 2
}