CSE 14 Lecture Notes - Lecture 14: Bubble Sort

46 views5 pages
17 May 2018
School
Course
Professor
CMPS12A Lecture 14 Sorting and Searching through Arrays
There are many ways of finding values in an array that are entered by the user. Loops must be
implemented in order to iterate through the arrays and functions make your life easier when
dealing with these methods. Values in an array can also be sorted in any order that you want it
to, given the correct algorithm for it. Here in BubbleSort, the method swaps values from least
value to greatest.
Example:
class BubbleSort {
public static void main(String[] args) {
double [] A = {7.0, 6.0, 5.0, -2.0, 2.3, 8.4, -1.5}
sort(A);
for (int i = 0; i<A.length; i++) {
Syste.out.pritA[i] + “ “;
System.out.println();
}
static void sort(double [] a) {
int i, n;
for (n = a.length; n>1; n--) {
for (i=0; i<n-1; i++) {
if (a[i] > a[i+1])
swap(a, i, i+1);
}
}
}
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in
static void swap(double [] a, int i, int j) {
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
The only thing with this sort is that the values in the array are only swapped through one
iteration of the array. Thus, the whole array would not be from least to greatest; bubblesort
basically just switches the current index from the next one, then goes to the next index and
switches the current one with the next one, and so on till the last index, ONLY if the current one
is greater than the next one. If one wanted to change the whole array from least to greatest,
you would need to call on the sort function many times until you get the desired result.
Here is a picture of how it would look like:
To find a given target in an array, you would want to do a Sequential Search, iterating through
the array until it finds the target, thus giving you the index where the target was found.
static int SeqSearch(int[] a, int t) {
for (int i = 0; i<a.length; i++) {
if (a[i] == t)
return i;
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents