So I was going through different sorting algorithms. But almost all the sorting algorithms require 2 loops to sort the array. The time complexity of Bubble sort & Insert
This can be used to sort array usinga single loop:- Points to be noed:
Code:
void sort(int *arr,int size){
int i;
for (i = 0; i <size; i++){
if(arr[i]>arr[i+1]){
arr[i]=arr[i]+arr[i+1];
arr[i+1]=arr[i]-arr[i+1];
arr[i]=arr[i]-arr[i+1];
if(i==size-2){
printf("%s\n","inside if loop" );
i=-1;
size--;
}
}
}
}
In the general case you have O(n lg n) as an average.
But in particular cases, the best case is O(n), which I consider close enough to what you'd call "only one loop", even though the implementation may show more than one instance of the for
keyword. And the good news with that, is that you're not depending on luck to make your best case a reality. Provided you know a few properties about your data, you can pick some specific algorithms. For example :
Those are but three examples. There are many more, way too many to recall from the top of my head, for many types of constrained data sets. If you have a real-life case at hand where O(n lg n) is not good enough, it's well worth doing some proper research, provided you identified a few interesting properties in your data.
public class SinleLoopeSorting {
public static void main(String[] args) {
Integer[] x = new Integer[] { 1, 7, 8, 0, 4, 2, 3 };
for (int i = 0; i < x.length - 1; i++) {
if (x[i] > x[i + 1]) {
int p = x[i];
x[i] = x[i + 1];
x[i + 1] = p;
i = -1;
}
}
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
}
}
Single for
loop for insertion sort:
strong text
function insertionSort (array) {
for(var i = 1 ; i < array.length ;){
if(array[1] < array[0]) {
temp = array[i];
array[i] = array[i -1];
array[i -1] = temp;
}
if(array[i] < array[i-1]){
var temp = array[i]
array[i] = array[i -1]
array[i -1] = temp
i--
} else{i++}
}
return array
}