Bubblesort() Function

Recommended Posts

hi guys function bubbleSort(arr,dir){var start, end;if(dir === 1){start = 0;end = arr.length;}else if(dir === -1){start = arr.length-1;end = -1;}var unsorted = true;while(unsorted){unsorted = false;for(i = start; i !=end; i=i+dir){if(arr[i+dir] && arr.value > arr[i+dir].value){var a = arr;var b = arr[i+dir];var c = a;arr = b;arr[i+dir] = c;unsorted = true;}}}return arr;}here what confuse me is the swapping why the c is assigned to the a couldn't just i swap them like thata = arr;b = arr[i+dir];a = b;b =arr;

Share on other sites

No, the values aren't saved like that. Assume in that line that arr contains the number "5". When you do this:a = arr;The variable a doesn't point to the same place in memory that arr points to, the value just gets copied. So after that line, both a and arr equal the value "5", but they don't point to the same place so when you update one it's not going to update the other one.So, assume that arr is "5", and that arr[i + dir] is "8". This is what happens when you run that code:

`a = arr[i];	   // a=5, b=undefined, arr[i]=5, arr[i+dir]=8b = arr[i+dir];   // a=5, b=8, arr[i]=5, arr[i+dir]=8a = b;			// a=8, b=8, arr[i]=5, arr[i+dir]=8b =arr[i];		// a=8, b=5, arr[i]=5, arr[i+dir]=8`

Notice how at the end arr and arr[i + dir] have the same value, they haven't changed. Look at what happens when you run the original code:

`var a = arr[i];	 //a=5, b=undefined, c=undefined, arr[i]=5, arr[i+dir]=8var b = arr[i+dir]; //a=5, b=8, c=undefined, arr[i]=5, arr[i+dir]=8var c = a;		  //a=5, b=8, c=5, arr[i]=5, arr[i+dir]=8arr[i] = b;		 //a=5, b=8, c=5, arr[i]=8, arr[i+dir]=8arr[i+dir] = c;	 //a=5, b=8, c=5, arr[i]=8, arr[i+dir]=5`

After that, both arr and arr[i+dir] are switched, the values have been swapped. They actually don't need to use all of those variables though, you can swap two variables with just one extra temporary variable:

`var tmp = arr[i];	 //tmp=5, arr[i]=5, arr[i+dir]=8arr[i] = arr[i+dir];  //tmp=5, arr[i]=8, arr[i+dir]=8arr[i+dir] = tmp;	 //tmp=5, arr[i]=8, arr[i+dir]=5`

That's the same result, the two values have been switched.