How to sort an array in a single loop?bubble sort by only single loopWhat should be the time complexity of my sorting algorithm?How do I check if an array includes an object in JavaScript?How do I sort a dictionary by value?Sorting an array of JavaScript objects by propertySort array of objects by string property valueFastest sort of fixed length 6 int arrayImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow to find time complexity of an algorithmHow to pair socks from a pile efficiently?How can I sort arrays and data in PHP?Swift Beta performance: sorting arrays
How to tell your grandparent to not come to fetch you with their car?
How to officially communicate to a non-responsive colleague?
PhD - Well known professor or well known school?
What does the term "railed" mean in signal processing?
How do governments keep track of their issued currency?
"You've got another thing coming" - translation into French
When conversion from Integer to Single may lose precision
How can drunken, homicidal elves successfully conduct a wild hunt?
Is it possible to 'live off the sea'
Genetic limitations to learn certain instruments
Is the term 'open source' a trademark?
Why would future John risk sending back a T-800 to save his younger self?
Why only the fundamental frequency component is said to give useful power?
Do any instruments not produce overtones?
Does an ice chest packed full of frozen food need ice?
Should I give professor gift at the beginning of my PhD?
Can the poison from Kingsmen be concocted?
Can a user sell my software (MIT license) without modification?
What's the largest optical telescope mirror ever put in space?
Which comes first? Multiple Imputation, Splitting into train/test, or Standardization/Normalization
Why doesn't Adrian Toomes give up Spider-Man's identity?
What are the peak hours for public transportation in Paris?
What is wrong with this proof that symmetric matrices commute?
Using "subway" as name for London Underground?
How to sort an array in a single loop?
bubble sort by only single loopWhat should be the time complexity of my sorting algorithm?How do I check if an array includes an object in JavaScript?How do I sort a dictionary by value?Sorting an array of JavaScript objects by propertySort array of objects by string property valueFastest sort of fixed length 6 int arrayImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow to find time complexity of an algorithmHow to pair socks from a pile efficiently?How can I sort arrays and data in PHP?Swift Beta performance: sorting arrays
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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 & Insertion sort is O(n) for Best case but is O(n^2) as worst case which again requires 2 loops. Is there a way to sort an array in a single loop?
algorithm sorting quicksort insertion-sort heapsort
add a comment |
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 & Insertion sort is O(n) for Best case but is O(n^2) as worst case which again requires 2 loops. Is there a way to sort an array in a single loop?
algorithm sorting quicksort insertion-sort heapsort
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
2
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03
add a comment |
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 & Insertion sort is O(n) for Best case but is O(n^2) as worst case which again requires 2 loops. Is there a way to sort an array in a single loop?
algorithm sorting quicksort insertion-sort heapsort
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 & Insertion sort is O(n) for Best case but is O(n^2) as worst case which again requires 2 loops. Is there a way to sort an array in a single loop?
algorithm sorting quicksort insertion-sort heapsort
algorithm sorting quicksort insertion-sort heapsort
asked Aug 12 '15 at 14:52
Aishwarya RAishwarya R
1922520
1922520
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
2
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03
add a comment |
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
2
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
2
2
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03
add a comment |
16 Answers
16
active
oldest
votes
Here, a single-loop Bubble Sort in Python:
def bubbly_sortish(data):
for _ in xrange(len(data)**2):
i, j = _/len(data), _%len(data)
if i<j and data[i] > data[j]:
data[i], data[j] = data[j], data[i]
A = [5, 1, 2, 3, 5, 6, 10]
bubbly_sortish(A)
print A
Of course this is a joke. But this shows the number of loops has little to do with algorithm complexity.
Now, if you're asking if it is possible to sort an array with O(n) comparisons, no, it's not possible. The lower bound is Ω(n log n) for comparison-based sorting algorithms.
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
|
show 1 more comment
Single Loop Bubble Sort using C++
int a[7]=5,7,6,2,4,3,1;
int temp = 0;
int j = 0;
for(int i = 0 ; i<a[]-1 ; i++)
int flag = 0;
if(a[i]>a[i+1])
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
if(i == 7-2-j)
if(!flag) break;
i = -1;
j++;
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number ofa
s elements, and a telling name instead offlag
.
– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
add a comment |
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 :
- 3-way quicksort runs very near O(n) when you have a lot of items with only a few distinct sorting keys (think server log entries as items and dates as keys).
- Counting sort runs in O(n+k) if your keys are easily indexable (like a character set, or small integers), and the index has a known upper bound k.
- Burstsort will run in O(wn) if you're dealing with strings of maximum length w.
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.
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
add a comment |
int list[] = 45, 78, 22, 96, 10, 87, 68, 2 ;
for (int i = 1; i < list.length; i++)
if (list[i] < list[i - 1])
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
System.out.print("Sorted array is : ");
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
add a comment |
Here is a working version for your given example:
One very fast efficiant and logical way of doing the problem works if you know the range of the values to be sorted, for example 0 <= val <= 100
where val is integer.
Then you can do it with a single read and write operation in only two loops... one for reading the array, one for writing it sorted:
Use a second array where the indices represent values 0-100, store in it the number of times every value 0-100 is encountered, for example val = 100
could exist 234 times in your target array...
There is only one loop for reading and one loop for writing, which is computationally as efficient as one loop which would do both the reading and the writing and faster than a loop that uses comparison... If you insist, you can do it in a single loop twice as long as the target array's length and reset i value to zero on the new array write operation.
The second loop simply writes in order the count of every value encountered in the first array.
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
add a comment |
Single loop array sort:
for(int i = 0, j=i+1; i < arr.length && j<arr.length;)
if(arr[i] > arr[j])
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i=0;
j=i+1;
else
i++;
j++;
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
add a comment |
javascript:
function bruteForce(arr)
for(var i=0;i<arr.length; )
if(arr[i+1]< arr[i])
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
else i++;
return arr;
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
add a comment |
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1
if array[i] > array[i + 1]
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
i = i + 1;
print(array)
add a comment |
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--
elsei++
return array
add a comment |
public void sortArrayUsingSingleLoop(int[] intArray)
int temp;
boolean swap = false;
for(int i=0;i<intArray.length-1;i++)
if(intArray[i]>intArray[i+1])
temp=intArray[i];
intArray[i]=intArray[i+1];
intArray[i+1]=temp;
swap=true;
if(swap &&i==intArray.length-2)
i=-1;swap=false;
add a comment |
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++)
if($a[$i] > $a[$i+1])
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
print_r($a);
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
add a comment |
def my_sort(num_list):
x = 0
while x < len(num_list) - 1:
if num_list[x] > num_list[x+1]:
num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
x = -1
x += 1
return num_list
print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
#output [14, 21, 27, 42, 43, 45, 46, 57, 70]
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
add a comment |
Sorting an array using single loop (javascript)
var arr = [4,5,2,10,3,7,11,5,1];
for(var i = 1; i < arr.length; 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];
i=0;
output : arr = [1, 2, 3, 4, 5, 5, 7, 10, 11]
add a comment |
The following code is in PHP to sort an array best case possible.
https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a)
$n = count($a);
$lt = [];
$gt = [];
if($n < 2)
return $a;
else
$f = $a[0];
for($i = 1;$i < $n ;$i++)
if($a[$i] > $f)
$gt [] = $a[$i];
else
$lt [] = $a[$i];
return array_merge(quicksort($lt),array($f),quicksort($gt));
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
add a comment |
Sorting an array using java in Single Loop:
public int[] getSortedArrayInOneLoop(int[] arr)
int temp;
int j;
for (int i = 1; i < arr.length; i++)
j = i - 1;
if (arr[i] < arr[j])
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i = 1;
return arr;
add a comment |
Late to the party but hope this helps
java solution
for(int i=1;i< arr.length;i++)
if(arr[i] < arr[i-1] )
arr[i-1] += arr[i];
arr[i] = arr[i-1] - arr[i];
arr[i-1] -= arr[i];
i=0;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31968697%2fhow-to-sort-an-array-in-a-single-loop%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
16 Answers
16
active
oldest
votes
16 Answers
16
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here, a single-loop Bubble Sort in Python:
def bubbly_sortish(data):
for _ in xrange(len(data)**2):
i, j = _/len(data), _%len(data)
if i<j and data[i] > data[j]:
data[i], data[j] = data[j], data[i]
A = [5, 1, 2, 3, 5, 6, 10]
bubbly_sortish(A)
print A
Of course this is a joke. But this shows the number of loops has little to do with algorithm complexity.
Now, if you're asking if it is possible to sort an array with O(n) comparisons, no, it's not possible. The lower bound is Ω(n log n) for comparison-based sorting algorithms.
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
|
show 1 more comment
Here, a single-loop Bubble Sort in Python:
def bubbly_sortish(data):
for _ in xrange(len(data)**2):
i, j = _/len(data), _%len(data)
if i<j and data[i] > data[j]:
data[i], data[j] = data[j], data[i]
A = [5, 1, 2, 3, 5, 6, 10]
bubbly_sortish(A)
print A
Of course this is a joke. But this shows the number of loops has little to do with algorithm complexity.
Now, if you're asking if it is possible to sort an array with O(n) comparisons, no, it's not possible. The lower bound is Ω(n log n) for comparison-based sorting algorithms.
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
|
show 1 more comment
Here, a single-loop Bubble Sort in Python:
def bubbly_sortish(data):
for _ in xrange(len(data)**2):
i, j = _/len(data), _%len(data)
if i<j and data[i] > data[j]:
data[i], data[j] = data[j], data[i]
A = [5, 1, 2, 3, 5, 6, 10]
bubbly_sortish(A)
print A
Of course this is a joke. But this shows the number of loops has little to do with algorithm complexity.
Now, if you're asking if it is possible to sort an array with O(n) comparisons, no, it's not possible. The lower bound is Ω(n log n) for comparison-based sorting algorithms.
Here, a single-loop Bubble Sort in Python:
def bubbly_sortish(data):
for _ in xrange(len(data)**2):
i, j = _/len(data), _%len(data)
if i<j and data[i] > data[j]:
data[i], data[j] = data[j], data[i]
A = [5, 1, 2, 3, 5, 6, 10]
bubbly_sortish(A)
print A
Of course this is a joke. But this shows the number of loops has little to do with algorithm complexity.
Now, if you're asking if it is possible to sort an array with O(n) comparisons, no, it's not possible. The lower bound is Ω(n log n) for comparison-based sorting algorithms.
edited Aug 12 '15 at 15:04
answered Aug 12 '15 at 14:59
Juan LopesJuan Lopes
8,67622039
8,67622039
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
|
show 1 more comment
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
3
3
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
Sure it's possible. The quantum bogosort algorithm is O(n)!
– Tripp Kinetics
Aug 12 '15 at 15:08
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@MrSmith42 That's bogosort. Not quantum bogosort.
– Tripp Kinetics
Aug 12 '15 at 15:38
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
@Tripp Kinetics: Ok but you cannot implement it on a usual computer because you need all these universes. So for all now existing computers the lower bound Ω(n log n) is still valid.
– MrSmith42
Aug 12 '15 at 15:55
1
1
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
@MrSmith42 The universes exist already. The hard part is destroying this universe if the array isn't sorted. Besides, algorithms are a concept independent of computers.
– Tripp Kinetics
Aug 12 '15 at 15:58
4
4
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
@TrippKinetics Not really. Algorithm complexity is intrinsically tied to the machine model the algorithm is supposed to run on. Would you say there are polynomial algorithms for all NP problems? But for a non-deterministic Turing machine this is just true. But no one says that. Even if bogosort could be solved by a "traditional" quantum computer, it would be in BQP, not P (necessarily)... and I think we got this joke just too far :)
– Juan Lopes
Aug 12 '15 at 20:21
|
show 1 more comment
Single Loop Bubble Sort using C++
int a[7]=5,7,6,2,4,3,1;
int temp = 0;
int j = 0;
for(int i = 0 ; i<a[]-1 ; i++)
int flag = 0;
if(a[i]>a[i+1])
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
if(i == 7-2-j)
if(!flag) break;
i = -1;
j++;
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number ofa
s elements, and a telling name instead offlag
.
– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
add a comment |
Single Loop Bubble Sort using C++
int a[7]=5,7,6,2,4,3,1;
int temp = 0;
int j = 0;
for(int i = 0 ; i<a[]-1 ; i++)
int flag = 0;
if(a[i]>a[i+1])
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
if(i == 7-2-j)
if(!flag) break;
i = -1;
j++;
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number ofa
s elements, and a telling name instead offlag
.
– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
add a comment |
Single Loop Bubble Sort using C++
int a[7]=5,7,6,2,4,3,1;
int temp = 0;
int j = 0;
for(int i = 0 ; i<a[]-1 ; i++)
int flag = 0;
if(a[i]>a[i+1])
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
if(i == 7-2-j)
if(!flag) break;
i = -1;
j++;
Single Loop Bubble Sort using C++
int a[7]=5,7,6,2,4,3,1;
int temp = 0;
int j = 0;
for(int i = 0 ; i<a[]-1 ; i++)
int flag = 0;
if(a[i]>a[i+1])
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
if(i == 7-2-j)
if(!flag) break;
i = -1;
j++;
edited Nov 9 '15 at 10:16
Smittey
2,24672332
2,24672332
answered Nov 9 '15 at 9:29
Ari4Ari4
562410
562410
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number ofa
s elements, and a telling name instead offlag
.
– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
add a comment |
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number ofa
s elements, and a telling name instead offlag
.
– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number of
a
s elements, and a telling name instead of flag
.– greybeard
Nov 9 '15 at 10:53
Comment (inside!) your code (know [Doxygen](www.doxygen.org)?), use a symbolic constant for the number of
a
s elements, and a telling name instead of flag
.– greybeard
Nov 9 '15 at 10:53
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
People should mind that this is a specific array that can be sorted by one iteration of bubble sort.
– NONONONONO
Dec 3 '18 at 18:58
add a comment |
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 :
- 3-way quicksort runs very near O(n) when you have a lot of items with only a few distinct sorting keys (think server log entries as items and dates as keys).
- Counting sort runs in O(n+k) if your keys are easily indexable (like a character set, or small integers), and the index has a known upper bound k.
- Burstsort will run in O(wn) if you're dealing with strings of maximum length w.
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.
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
add a comment |
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 :
- 3-way quicksort runs very near O(n) when you have a lot of items with only a few distinct sorting keys (think server log entries as items and dates as keys).
- Counting sort runs in O(n+k) if your keys are easily indexable (like a character set, or small integers), and the index has a known upper bound k.
- Burstsort will run in O(wn) if you're dealing with strings of maximum length w.
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.
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
add a comment |
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 :
- 3-way quicksort runs very near O(n) when you have a lot of items with only a few distinct sorting keys (think server log entries as items and dates as keys).
- Counting sort runs in O(n+k) if your keys are easily indexable (like a character set, or small integers), and the index has a known upper bound k.
- Burstsort will run in O(wn) if you're dealing with strings of maximum length w.
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.
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 :
- 3-way quicksort runs very near O(n) when you have a lot of items with only a few distinct sorting keys (think server log entries as items and dates as keys).
- Counting sort runs in O(n+k) if your keys are easily indexable (like a character set, or small integers), and the index has a known upper bound k.
- Burstsort will run in O(wn) if you're dealing with strings of maximum length w.
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.
edited Feb 23 '17 at 10:29
answered Aug 12 '15 at 15:17
Mathias DolidonMathias Dolidon
2,2001123
2,2001123
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
add a comment |
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
1
1
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
Bear in mind that O(n lg n) is an average, not a lower bound. The lower bound is O(n) when the input is already sorted :)
– John Wu
Feb 22 '17 at 17:38
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
You're right, this was a bad mistake ! I'll correct my post immediately. Thank you very much !
– Mathias Dolidon
Feb 23 '17 at 10:28
add a comment |
int list[] = 45, 78, 22, 96, 10, 87, 68, 2 ;
for (int i = 1; i < list.length; i++)
if (list[i] < list[i - 1])
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
System.out.print("Sorted array is : ");
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
add a comment |
int list[] = 45, 78, 22, 96, 10, 87, 68, 2 ;
for (int i = 1; i < list.length; i++)
if (list[i] < list[i - 1])
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
System.out.print("Sorted array is : ");
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
add a comment |
int list[] = 45, 78, 22, 96, 10, 87, 68, 2 ;
for (int i = 1; i < list.length; i++)
if (list[i] < list[i - 1])
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
System.out.print("Sorted array is : ");
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
int list[] = 45, 78, 22, 96, 10, 87, 68, 2 ;
for (int i = 1; i < list.length; i++)
if (list[i] < list[i - 1])
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
System.out.print("Sorted array is : ");
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
answered Dec 4 '18 at 6:48
Lokendra solankiLokendra solanki
313
313
add a comment |
add a comment |
Here is a working version for your given example:
One very fast efficiant and logical way of doing the problem works if you know the range of the values to be sorted, for example 0 <= val <= 100
where val is integer.
Then you can do it with a single read and write operation in only two loops... one for reading the array, one for writing it sorted:
Use a second array where the indices represent values 0-100, store in it the number of times every value 0-100 is encountered, for example val = 100
could exist 234 times in your target array...
There is only one loop for reading and one loop for writing, which is computationally as efficient as one loop which would do both the reading and the writing and faster than a loop that uses comparison... If you insist, you can do it in a single loop twice as long as the target array's length and reset i value to zero on the new array write operation.
The second loop simply writes in order the count of every value encountered in the first array.
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
add a comment |
Here is a working version for your given example:
One very fast efficiant and logical way of doing the problem works if you know the range of the values to be sorted, for example 0 <= val <= 100
where val is integer.
Then you can do it with a single read and write operation in only two loops... one for reading the array, one for writing it sorted:
Use a second array where the indices represent values 0-100, store in it the number of times every value 0-100 is encountered, for example val = 100
could exist 234 times in your target array...
There is only one loop for reading and one loop for writing, which is computationally as efficient as one loop which would do both the reading and the writing and faster than a loop that uses comparison... If you insist, you can do it in a single loop twice as long as the target array's length and reset i value to zero on the new array write operation.
The second loop simply writes in order the count of every value encountered in the first array.
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
add a comment |
Here is a working version for your given example:
One very fast efficiant and logical way of doing the problem works if you know the range of the values to be sorted, for example 0 <= val <= 100
where val is integer.
Then you can do it with a single read and write operation in only two loops... one for reading the array, one for writing it sorted:
Use a second array where the indices represent values 0-100, store in it the number of times every value 0-100 is encountered, for example val = 100
could exist 234 times in your target array...
There is only one loop for reading and one loop for writing, which is computationally as efficient as one loop which would do both the reading and the writing and faster than a loop that uses comparison... If you insist, you can do it in a single loop twice as long as the target array's length and reset i value to zero on the new array write operation.
The second loop simply writes in order the count of every value encountered in the first array.
Here is a working version for your given example:
One very fast efficiant and logical way of doing the problem works if you know the range of the values to be sorted, for example 0 <= val <= 100
where val is integer.
Then you can do it with a single read and write operation in only two loops... one for reading the array, one for writing it sorted:
Use a second array where the indices represent values 0-100, store in it the number of times every value 0-100 is encountered, for example val = 100
could exist 234 times in your target array...
There is only one loop for reading and one loop for writing, which is computationally as efficient as one loop which would do both the reading and the writing and faster than a loop that uses comparison... If you insist, you can do it in a single loop twice as long as the target array's length and reset i value to zero on the new array write operation.
The second loop simply writes in order the count of every value encountered in the first array.
edited Feb 22 '17 at 19:00
answered Feb 22 '17 at 15:05
com.prehensiblecom.prehensible
1,26311122
1,26311122
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
add a comment |
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
1
1
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
This (known as a pigeonhole sort) is the only true example of a single loop sort that operates in O(n) time. Like any other sorting example, a loop is required to display the results, but only after the sorting is complete.
– John Wu
Feb 22 '17 at 17:36
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
According ot Wiki, Pigeonhole sort is a mathematical concept rather than a programming array process, although pigeonhole sorting of arrays is very common. I used this solution to sort 10 million points in less than 1-2 seconds, its very easy to program and has near maximum efficiency for num instructions, it is literally 12 lines of code.
– com.prehensible
Feb 27 '17 at 10:15
add a comment |
Single loop array sort:
for(int i = 0, j=i+1; i < arr.length && j<arr.length;)
if(arr[i] > arr[j])
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i=0;
j=i+1;
else
i++;
j++;
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
add a comment |
Single loop array sort:
for(int i = 0, j=i+1; i < arr.length && j<arr.length;)
if(arr[i] > arr[j])
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i=0;
j=i+1;
else
i++;
j++;
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
add a comment |
Single loop array sort:
for(int i = 0, j=i+1; i < arr.length && j<arr.length;)
if(arr[i] > arr[j])
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i=0;
j=i+1;
else
i++;
j++;
Single loop array sort:
for(int i = 0, j=i+1; i < arr.length && j<arr.length;)
if(arr[i] > arr[j])
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i=0;
j=i+1;
else
i++;
j++;
edited May 16 '17 at 17:36
Jen R
1,3691221
1,3691221
answered May 16 '17 at 14:00
Anil MuleAnil Mule
163
163
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
add a comment |
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
please, edit your answer to formatting issues
– user4074041
May 16 '17 at 14:30
add a comment |
javascript:
function bruteForce(arr)
for(var i=0;i<arr.length; )
if(arr[i+1]< arr[i])
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
else i++;
return arr;
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
add a comment |
javascript:
function bruteForce(arr)
for(var i=0;i<arr.length; )
if(arr[i+1]< arr[i])
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
else i++;
return arr;
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
add a comment |
javascript:
function bruteForce(arr)
for(var i=0;i<arr.length; )
if(arr[i+1]< arr[i])
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
else i++;
return arr;
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
javascript:
function bruteForce(arr)
for(var i=0;i<arr.length; )
if(arr[i+1]< arr[i])
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
else i++;
return arr;
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
edited Jan 24 '18 at 18:50
Quality Catalyst
4,45752551
4,45752551
answered Jan 24 '18 at 10:09
shakthi nagarajshakthi nagaraj
343
343
add a comment |
add a comment |
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1
if array[i] > array[i + 1]
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
i = i + 1;
print(array)
add a comment |
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1
if array[i] > array[i + 1]
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
i = i + 1;
print(array)
add a comment |
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1
if array[i] > array[i + 1]
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
i = i + 1;
print(array)
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1
if array[i] > array[i + 1]
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
i = i + 1;
print(array)
answered Jun 12 '18 at 9:22
Jatin ChauhanJatin Chauhan
758518
758518
add a comment |
add a comment |
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--
elsei++
return array
add a comment |
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--
elsei++
return array
add a comment |
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--
elsei++
return array
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--
elsei++
return array
edited Aug 1 '18 at 4:52
Community♦
11
11
answered Dec 5 '15 at 19:30
Vaibhav NamburiVaibhav Namburi
56124
56124
add a comment |
add a comment |
public void sortArrayUsingSingleLoop(int[] intArray)
int temp;
boolean swap = false;
for(int i=0;i<intArray.length-1;i++)
if(intArray[i]>intArray[i+1])
temp=intArray[i];
intArray[i]=intArray[i+1];
intArray[i+1]=temp;
swap=true;
if(swap &&i==intArray.length-2)
i=-1;swap=false;
add a comment |
public void sortArrayUsingSingleLoop(int[] intArray)
int temp;
boolean swap = false;
for(int i=0;i<intArray.length-1;i++)
if(intArray[i]>intArray[i+1])
temp=intArray[i];
intArray[i]=intArray[i+1];
intArray[i+1]=temp;
swap=true;
if(swap &&i==intArray.length-2)
i=-1;swap=false;
add a comment |
public void sortArrayUsingSingleLoop(int[] intArray)
int temp;
boolean swap = false;
for(int i=0;i<intArray.length-1;i++)
if(intArray[i]>intArray[i+1])
temp=intArray[i];
intArray[i]=intArray[i+1];
intArray[i+1]=temp;
swap=true;
if(swap &&i==intArray.length-2)
i=-1;swap=false;
public void sortArrayUsingSingleLoop(int[] intArray)
int temp;
boolean swap = false;
for(int i=0;i<intArray.length-1;i++)
if(intArray[i]>intArray[i+1])
temp=intArray[i];
intArray[i]=intArray[i+1];
intArray[i+1]=temp;
swap=true;
if(swap &&i==intArray.length-2)
i=-1;swap=false;
answered Sep 18 '18 at 11:37
Krishna Mohan SinghKrishna Mohan Singh
22936
22936
add a comment |
add a comment |
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++)
if($a[$i] > $a[$i+1])
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
print_r($a);
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
add a comment |
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++)
if($a[$i] > $a[$i+1])
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
print_r($a);
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
add a comment |
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++)
if($a[$i] > $a[$i+1])
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
print_r($a);
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++)
if($a[$i] > $a[$i+1])
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
print_r($a);
edited Mar 23 at 11:19
answered Mar 15 at 19:14
puneet jainpuneet jain
215
215
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
add a comment |
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
2
2
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
It could be helpful if you added some context to your answer.
– chakeda
Mar 15 at 19:33
1
1
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
This is essentially bubble sort in what language? Could be perl or shell script without context, people have a hard time understanding.
– Kemin Zhou
Mar 15 at 21:49
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
Sorry for not giving the context. The following code is in php. you can test the code on phpfiddle.org.
– puneet jain
Mar 18 at 8:09
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
@puneetjain Edit the answer with the above comment. Comments are for reviewers not for additional info from the author. You could additional use Edit1/Edit2/ etc markers in case of unrelated info to the answer to a specific comment. Happy using SO.
– baymax
Mar 22 at 12:18
add a comment |
def my_sort(num_list):
x = 0
while x < len(num_list) - 1:
if num_list[x] > num_list[x+1]:
num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
x = -1
x += 1
return num_list
print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
#output [14, 21, 27, 42, 43, 45, 46, 57, 70]
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
add a comment |
def my_sort(num_list):
x = 0
while x < len(num_list) - 1:
if num_list[x] > num_list[x+1]:
num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
x = -1
x += 1
return num_list
print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
#output [14, 21, 27, 42, 43, 45, 46, 57, 70]
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
add a comment |
def my_sort(num_list):
x = 0
while x < len(num_list) - 1:
if num_list[x] > num_list[x+1]:
num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
x = -1
x += 1
return num_list
print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
#output [14, 21, 27, 42, 43, 45, 46, 57, 70]
def my_sort(num_list):
x = 0
while x < len(num_list) - 1:
if num_list[x] > num_list[x+1]:
num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
x = -1
x += 1
return num_list
print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
#output [14, 21, 27, 42, 43, 45, 46, 57, 70]
edited Jul 10 '18 at 7:54
answered Jul 10 '18 at 7:04
Om trivediOm trivedi
323
323
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
add a comment |
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
3
3
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
– sɐunıɔןɐqɐp
Jul 10 '18 at 7:12
add a comment |
Sorting an array using single loop (javascript)
var arr = [4,5,2,10,3,7,11,5,1];
for(var i = 1; i < arr.length; 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];
i=0;
output : arr = [1, 2, 3, 4, 5, 5, 7, 10, 11]
add a comment |
Sorting an array using single loop (javascript)
var arr = [4,5,2,10,3,7,11,5,1];
for(var i = 1; i < arr.length; 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];
i=0;
output : arr = [1, 2, 3, 4, 5, 5, 7, 10, 11]
add a comment |
Sorting an array using single loop (javascript)
var arr = [4,5,2,10,3,7,11,5,1];
for(var i = 1; i < arr.length; 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];
i=0;
output : arr = [1, 2, 3, 4, 5, 5, 7, 10, 11]
Sorting an array using single loop (javascript)
var arr = [4,5,2,10,3,7,11,5,1];
for(var i = 1; i < arr.length; 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];
i=0;
output : arr = [1, 2, 3, 4, 5, 5, 7, 10, 11]
edited Mar 4 at 9:17
answered Mar 4 at 6:42
Sk AsifSk Asif
186
186
add a comment |
add a comment |
The following code is in PHP to sort an array best case possible.
https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a)
$n = count($a);
$lt = [];
$gt = [];
if($n < 2)
return $a;
else
$f = $a[0];
for($i = 1;$i < $n ;$i++)
if($a[$i] > $f)
$gt [] = $a[$i];
else
$lt [] = $a[$i];
return array_merge(quicksort($lt),array($f),quicksort($gt));
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
add a comment |
The following code is in PHP to sort an array best case possible.
https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a)
$n = count($a);
$lt = [];
$gt = [];
if($n < 2)
return $a;
else
$f = $a[0];
for($i = 1;$i < $n ;$i++)
if($a[$i] > $f)
$gt [] = $a[$i];
else
$lt [] = $a[$i];
return array_merge(quicksort($lt),array($f),quicksort($gt));
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
add a comment |
The following code is in PHP to sort an array best case possible.
https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a)
$n = count($a);
$lt = [];
$gt = [];
if($n < 2)
return $a;
else
$f = $a[0];
for($i = 1;$i < $n ;$i++)
if($a[$i] > $f)
$gt [] = $a[$i];
else
$lt [] = $a[$i];
return array_merge(quicksort($lt),array($f),quicksort($gt));
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
The following code is in PHP to sort an array best case possible.
https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a)
$n = count($a);
$lt = [];
$gt = [];
if($n < 2)
return $a;
else
$f = $a[0];
for($i = 1;$i < $n ;$i++)
if($a[$i] > $f)
$gt [] = $a[$i];
else
$lt [] = $a[$i];
return array_merge(quicksort($lt),array($f),quicksort($gt));
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
answered Mar 24 at 16:28
puneet jainpuneet jain
215
215
add a comment |
add a comment |
Sorting an array using java in Single Loop:
public int[] getSortedArrayInOneLoop(int[] arr)
int temp;
int j;
for (int i = 1; i < arr.length; i++)
j = i - 1;
if (arr[i] < arr[j])
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i = 1;
return arr;
add a comment |
Sorting an array using java in Single Loop:
public int[] getSortedArrayInOneLoop(int[] arr)
int temp;
int j;
for (int i = 1; i < arr.length; i++)
j = i - 1;
if (arr[i] < arr[j])
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i = 1;
return arr;
add a comment |
Sorting an array using java in Single Loop:
public int[] getSortedArrayInOneLoop(int[] arr)
int temp;
int j;
for (int i = 1; i < arr.length; i++)
j = i - 1;
if (arr[i] < arr[j])
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i = 1;
return arr;
Sorting an array using java in Single Loop:
public int[] getSortedArrayInOneLoop(int[] arr)
int temp;
int j;
for (int i = 1; i < arr.length; i++)
j = i - 1;
if (arr[i] < arr[j])
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i = 1;
return arr;
edited Mar 25 at 11:31
answered Mar 25 at 11:15
Amit KumarAmit Kumar
262
262
add a comment |
add a comment |
Late to the party but hope this helps
java solution
for(int i=1;i< arr.length;i++)
if(arr[i] < arr[i-1] )
arr[i-1] += arr[i];
arr[i] = arr[i-1] - arr[i];
arr[i-1] -= arr[i];
i=0;
add a comment |
Late to the party but hope this helps
java solution
for(int i=1;i< arr.length;i++)
if(arr[i] < arr[i-1] )
arr[i-1] += arr[i];
arr[i] = arr[i-1] - arr[i];
arr[i-1] -= arr[i];
i=0;
add a comment |
Late to the party but hope this helps
java solution
for(int i=1;i< arr.length;i++)
if(arr[i] < arr[i-1] )
arr[i-1] += arr[i];
arr[i] = arr[i-1] - arr[i];
arr[i-1] -= arr[i];
i=0;
Late to the party but hope this helps
java solution
for(int i=1;i< arr.length;i++)
if(arr[i] < arr[i-1] )
arr[i-1] += arr[i];
arr[i] = arr[i-1] - arr[i];
arr[i-1] -= arr[i];
i=0;
answered Apr 17 at 21:43
Nour El-Deen Abou El-KassemNour El-Deen Abou El-Kassem
12
12
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31968697%2fhow-to-sort-an-array-in-a-single-loop%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I'm not sure what you mean by "one loop" vs. "two loops". You mean you want to sort without nested loops?
– Tripp Kinetics
Aug 12 '15 at 14:56
2
The only thing that comes to mind is counting or bin sort, but those require that all of the values be within a predefined range.
– beaker
Aug 12 '15 at 15:03