Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

how does sorting array works in c++

/*
so lets create an array called 'arr' which is size of n and iterate ever it with
double loop and since we want to sort the array, then we want to place lowest 
values of the array, at the very beggining of it, so while iterating, we keep 
the lowest values we meet, and replace it with the current position.

for example:                                         
if we arecurrenty at the index 2, and array looks like this : [0,1,5,6,2,3], our 
current value is 5, so when iterating to the end, our minimal value should be 2,
and if we swipe their indexes, it will look like this : [0,1,2,6,5,3].
if we do exact same operation, but with the next index which is 3(because 
previous index was 2), our current value is 6, and if we iterate over it, we
meet the minimal value of 3, so when we swap their positions, we get something
like this : [0,1,2,3,5,6]. and thats it, our array is sorted.But iteration is
not finished yet, we are still at index 4, but our value is 5, and the minimal
value on the right side of it is 6, which is more that our value, which means
we should skip this part, and only after this, our alglorithm is over which looks
something like this:
*/
for(int i = 0; i < n-1; i++){
	int curr = arr[i]; // current minimal value
    int indx = i; // index of current minimal value
    for(int j = i; j < n; j++){ // iterating on eveny value that is on right side
     	if(curr > arr[j]){// if some value is less than current minimal,
        	curr = arr[j]; // we make it minimal
           	indx = j; // and it's index minimal.
        }
    }
// after all of that, we swap values of current position, and the minimal value
// using index of minimal value.
    int temp = arr[i]; 
  	arr[i] = arr[indx];
    arr[indx] = temp;
}
// I hope it helped you understanding how sorting works :)
// Good luck in your future projects.
Source by cplusplus.com #
 
PREVIOUS NEXT
Tagged: #sorting #array #works
ADD COMMENT
Topic
Name
7+5 =