paradox_71's blog

By paradox_71, history, 8 hours ago, In English

I recently worked on optimizing the insertion sort algorithm and wanted to share my approach with the community. This version uses a single loop to reduce the number of comparisons and swaps, making it more efficient for certain datasets.

Problem Statement Given an array of integers, sort the array in ascending order using an optimized version of the insertion sort algorithm that utilizes only one loop.

Approach The traditional insertion sort algorithm shifts elements one by one to their correct position. In my optimized version, I use a while loop to reduce the number of comparisons and swaps.

Code

include

using namespace std;

int main() { int n; cout << "Enter how many numbers you want as input: "; cin >> n; int arr[n]; cout << "Enter the elements: "; for (int i = 0; i < n; i++) { cin >> arr[i]; }

int i = 0; while (i != n) { if (i >= 1 && arr[i — 1] > arr[i]) { int temp = arr[i — 1]; arr[i — 1] = arr[i]; arr[i] = temp; i--; } else { i++; } }

cout << "Sorted: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } }

Explanation 1. Input Handling: The program first takes the number of elements and the elements themselves as input. 2. Sorting Logic: • The while loop iterates through the array.

• If the current element is smaller than the previous element, they are swapped, and the index is decremented to recheck the previous elements.

• If the current element is in the correct position, the index is incremented to move to the next element.

  1. Output: The sorted array is printed.

Conclusion This optimized version of insertion sort reduces the number of comparisons and swaps, making it more efficient for certain datasets. Feel free to share your thoughts or any further optimizations you might have!

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
7 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

cool idea. not sure id call it "optimized" as it does roughly twice as many pointer movements as normal insertion sort, rather id call it "golfed"

»
7 hours ago, # |
  Vote: I like it +17 Vote: I do not like it

isn't this just Gnome Sort? You ain't inventing anything new buddy