# AP Computer Science Java: Lesson 5.1Rearranging Data - Sort Methods

 AP Home Karel Unit 1 Unit 2 Unit 3 Unit 4 Unit 5 Unit 6 Unit 7 Progs Tests Back to Lesson 4.4 - The ArrayList Class On to Lesson 5.2 - Search Methods Lesson 5.1 - Sort Methods Purpose: To learn how to sort numbers and text stored in arrays Sort of...   We will now take data (numbers or text) stored in arrays and sort it. There are two orders in which to sort - ascending (lowest to highest) and descending (highest to lowest). In addition, there are numerous methods which can be use to sort an array. Let's learn three: BUBBLE, SELECTION, and INSERTION. For each of the following, we assume that list is defined as follows: int[] list = new int[n]; // n = some integer THE BUBBLE SORT ALGORITHM - descending order int i, j, temp; for(i=n-1; i>0; i--)    for(j=0; jlist[maxIndex])           maxIndex=j;    temp=list[maxIndex];    list[maxIndex]=list[i];    list[i]=temp; }   THE INSERTION SORT ALGORITHM - descending order int i, j, temp; for(i=1; i0 && list[j]>list[j-1])    {      temp=list[j];      list[j]=list[j-1];      list[j-1]=temp;      j--;    } }   Note that to change any of these to an ascending order sort, all we have to do is change the direction of the inequality symbol in the condition of the if. In closing, each sort method has its own technique for sorting. While the end result is the same, the path to that point isn't. Understand the general idea of how each sort works and don't bother memorizing the Java algorithm. Lastly, the bubble sort is fine for small arrays, but gets bogged down with too many comparisons and switches when we encounter a large collection of data. The selection and insertion are much faster in this case. Use either with approximately equal results in efficiency. Back to Lesson 4.4 - The ArrayList Class On to Lesson 5.2 - Search Methods AP Home Karel Unit 1 Unit 2 Unit 3 Unit 4 Unit 5 Unit 6 Unit 7 Progs Tests