rajivnt
asked on
Need A for Bubble Sort
Hello
Can Anybody give a code for bubble sorting in javascript
Required ASAP
Thkx
Can Anybody give a code for bubble sorting in javascript
Required ASAP
Thkx
And the compare function works like this>
function compare_cars(a,b) {
if(a < b) return -1;
if(a > b) return 1;
return 0
}
sorted_cars.sort(compare_c ars)
alert(sorted_cars)
You see?
function compare_cars(a,b) {
if(a < b) return -1;
if(a > b) return 1;
return 0
}
sorted_cars.sort(compare_c
alert(sorted_cars)
You see?
And here the bubble sort varianr only for compare:
function bubblesort( sortArray ) {
var al = sortArray.length;
var swap;
do {
swap = false;
for(i=0;i<al;i++) {
if(sortArray[i]>sortArray[ i+1]) {
var interValue = sortArray[i];
sortArray[i] = sortArray[i+1];
sortArray[i+1] = interValue;
swap=true;
}
}
} while (swap==true)
}
bubblesort(sorted_cars);
alert('bubbled: '+sorted_cars);
function bubblesort( sortArray ) {
var al = sortArray.length;
var swap;
do {
swap = false;
for(i=0;i<al;i++) {
if(sortArray[i]>sortArray[
var interValue = sortArray[i];
sortArray[i] = sortArray[i+1];
sortArray[i+1] = interValue;
swap=true;
}
}
} while (swap==true)
}
bubblesort(sorted_cars);
alert('bubbled: '+sorted_cars);
homework??
professional <|;-)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
OK, it is not such bad with this fixed loop bubbling.
It is: n*(n-1)/2
But still my adaptive loop needs n iterations for an array already sorted :-)
The fix loop sort needs n*(n-1)/2 also for this best case.
It is: n*(n-1)/2
But still my adaptive loop needs n iterations for an array already sorted :-)
The fix loop sort needs n*(n-1)/2 also for this best case.
ASKER
Thanks A lot Buddy
Thanks to you :-)
But next time give me an A+, OK!
So long,
zvonko
But next time give me an A+, OK!
So long,
zvonko
Bubble sort is one of primitive one.
Why not use the built in sort() function of JavaScript
As a parameter of built in sort you can pass your own compare function.
Here an example without sort parameter function:
<script>
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station
my_cars["big"]="SUV";
var i = 0;
var sorted_cars = new Array()
for(car in my_cars) {
sorted_cars[i] = [car, my_cars[car]]
i += 1;
}
sorted_cars.sort()
alert(sorted_cars)
</script>