i swap if not already in if correct position temp

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: allest } if (smallest != i) // swap if not already in if { // correct position temp = X[i]; X[i] = X[smallest]; X[smallest] = temp; } } swap values i and smallest Applied Programming Let's talk about efficiency: An alternative: for (i=0;i<n-1;i++) { smallest = i; // location of smallest so far for (j=i+1;j<n;j++) { if (X[smallest] > X[j]) smallest = j; // new loc of smallest } if (smallest != i) // swap if not already in if { // correct position swap X[i] with X[smallest] } } for (i=0;i<n-1;i++) { for (j=i+1;j<n;j++) { if (X[i] > X[j]) { temp = X[i]; X[i] = X[j]; X[j] = temp; } } } two nested for loops Why is this not as good? Applied Programming Let's talk about efficiency: Applied Programming Let's talk about efficiency: for (i=0;i<n-1;i++) { smallest = i; // location of smallest so far for (j=i+1;j<n;j++) { if (X[smallest] > X[j]) smallest = j; // new loc of smallest } if (smallest != i) // swap if not already in if { // correct position swap X[i] with X[smallest] } } two nested for loops outer one performed n-1 times Applied Programming for (i=0;i<n-1;i++) { smallest = i; // location of smallest so far for (j=i+1;j<n;j++) { if (X[smallest] > X[j]) smallest = j; // new loc of smallest } if (smallest != i) // swap if not already in if { // correct position swap X[i] with X[smallest] } } two nested for loops outer one performed n-1 times inner one varies Applied Programming Let's talk about efficiency: Let's talk about efficiency: for (i=0;i<n-1;i++) { smallest = i; // location of smallest so far for (j=i+1;j<n;j++) { if (X[smallest] > X[j]) smallest = j; // new loc of smallest } if (smallest != i) // swap if not already in if { // correct position swap X[i] with X[smallest] } } i=0 inner loop executed n-1 times i=1 inner loop executes n-2 times i=2 . . . n-3 times Applied Programming Applied Let's talk about efficiency: for (i=0;i<n-1;i++) { smallest = i; // location of smallest so far for (j=i+1;j<n;j++) { if (X[smallest] > X[j]...
View Full Document

Ask a homework question - tutors are online