{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

1c - Sorting1

# i swap if not already in if correct position swap

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ) smallest = j; // new loc of smallest } if (smallest != i) // swap if not already in if { // correct position swap X[i] with X[smallest] } } Each inner loop involves a comparison, so there are 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] } } 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] } } Each inner loop involves a comparison, so there are (n-1) Each inner loop involves a comparison, so there are (n-1)+(n-2) Applied Programming 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] } } 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] } } Each inner loop involves a comparison, so there are (n-1)+(n-2)+(n-3) Each inner loop involves a comparison, so there are (n-1)+(n-2)+(n-3)+ . . . + 1 Applied Programming 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] } } Each inner loop involves a comparison, so there are (n-1)+(n-2)+(n-3)+ . . . + 1 = n(n-1)/2 in tot...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online