Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.

Slides:



Advertisements
Similar presentations
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Advertisements

One Dimensional Arrays
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
CS102 A Wide Array of Possibilities CS 102 Java’s Central Casting.
Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers.
Simple Sorting Algorithms
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Programming Logic and Design Fourth Edition, Comprehensive
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
ITEC 2620A Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: 2620a.htm Office: TEL 3049.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
CSE 373 Data Structures and Algorithms
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
3 – SIMPLE SORTING ALGORITHMS
Function Overloading Two different functions may have the same name as long as they differ in the number or types of arguments: int max(int x, int y) and.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
COP 3540 Data Structures with OOP
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
For Friday Read No quiz Program 6 due. Program 6 Any questions?
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Prof. U V THETE Dept. of Computer Science YMA
Lecture 14 Searching and Sorting Richard Gesick.
Recitation 13 Searching and Sorting.
Simple Sorting Algorithms
Describing algorithms in pseudo code
Introduction to Programming
Selection sort Given an array of length n,
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays in Java What, why and how Copyright Curt Hill.
Lecture 11 Searching and Sorting Richard Gesick.
Loop Strategies Repetition Playbook.
Simple Sorting Algorithms
A Wide Array of Possibilities
Simple Sorting Algorithms
Simple Sorting Algorithms
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Module 8 – Searching & Sorting Algorithms
Arrays.
Presentation transcript:

Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments. The compartments are numbered (starting at 0) so that we can indicate which compartment we are referring to.

Creating an Array The notation for an an array of a given type is: [] For example, an array of int s is denoted by: int[]

Naming Arrays Just like other types, we can associate a name with a data object by assigning it a label – a variable: int[] grades; This declares grades to be of type array of int. But it does not create the array.

Creating an array To actually create the array, we must use the new operator, and specify the size of the array: int[] grades = new int[100]; This creates a new data object, which can hold 100 int s (numbered from 0 to 99) and sets the variable grades to refer to that new data object.

Using Arrays In mathematics, we have a notion of a vector, which is variable that holds a number of elements, e.g. x = {1, 7, 10, 20, 2, 9} An element is referred to by a subscript, e.g., x 1 would be 1, x 2 would be 7, and so forth. The variable is read “x sub 1” and “x sub 2.”

Java Arrays In Java, we do the same thing, but the notation is different: x[i] is still read “x sub i” and means the ith element of the array x. Not that in Java, arrays begin at 0, not 1.

Using Subscripts The value inside the square bracket can be a constant, a variable, or an expression, but must be an int. The point is that we can vary the expression in the brackets, so that x[i] can refer to different values, depending on the value of i. for(int i=0; i<100; i++) // read in 100 ints into grades grades[i] = sc.nextInt();

Example Arrays are useful for storing lists of data. For example, suppose that we wanted to calculate the standard deviation of a set of test grades. The formula is: standard deviation = where x is the average of x.

Example (cont'd) We would have to read in and store the grades, and compute the average first: int[] grades = new int[100]; int total = 0, num = 0; int grade = sc.nextInt(); while(grade >= 0) { total += grade; grades[num++] = grade; grade = sc.nextInt(); } double ave = (double)total/(double)num;

Example (cont'd) We would then have a second loop to compute the standard deviation. This loop can be a count- controlled loop: double total2 = 0; for(int i=0; i<num; i++) total2 = (grades[i] – average)* (grades[i] - average); double sd = Math.sqrt(total2/num);

Finding the Minimum We could also write a loop to find the minimum grade. (We've already done this once – this is to practice using arrays and loops.) int min = grades[0]; for(int i=1; i<num; i++) if(grades[i] < min) min = grades[i];

Sorting Arrays Note that we can use this to sort the array, i.e., put it in order from smallest to largest grade. We could find the smallest grade, and switch it with the first grade, find the next smallest grade, and switch it with the second grade, and so on. Note that it's not enough to find the smallest grade. We must find the position of the smallest grade in the array.

Finding the Position of the Min All we need to do is to remember the position of the minimum – originally 0, and then i, if a smaller grade is found. We must access the array to find the minimum grade in the comparison: int minpos = 0; for(int i=1; i<num; i++) if(grades[i] < grades[minpos]; minpos = i;

Swapping Once we find the position of the minimum grade, we can swap that grade with the grade at position 0. The code to swap a and b is: int t = a; a = b; b = t;

Swap Method We can write a method that swaps two elements of an array: private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

Arrays are Data Objects It is important to note that arrays are data objects, and array variables are object variables. Hence, array variables contain a reference to the data object, and not the data object themselves. When we use assignment on arrays, the reference is copied, and the two variables will point to the same data object. Similarly, when calling a method, the parameter and object refer to the same data object.

Sort (cont'd) After we find the position of the minimum grade, we can use the method to swap it with the element at position 0: int minpos = 0; for(int i=1; i<num; i++) if(grades[i] < grades[minpos]; minpos = i; swap(grades, 0, minpos);

Sort (cont'd) This only puts the smallest grade in place. For the other grades, we will need another loop: for(int j=0; j<num; j++) { int minpos = j; for(int i=minpos+1; i<num; i++) if(grades[i] < grades[minpos]; minpos = i; swap(grades, j, minpos); }

Selection Sort Note that minpos should start at j, and the inner loop begins at minpos+1 to find the smallest grade. Also, we note that if all but the last grades are in their right place, then the last grade must be also. So, in the outer loop, the test could be j < num-1. This sort is called Selection Sort, because we select the smallest element and put it into the right place.

Bubble Sort Another kind of sort “bubbles” the largest element up to the right place, by comparing each element to the one following it and swapping them if they are in the wrong order. Each pass guarantees that the largest will be forced to the end. After num passes (actually num-1 ) all the elements will be in the right places.

Bubble Sort (cont'd) Here's the code to move the largest to the end: for(j=0; j<num-1; j++) if(grades[j] > grades[j+1]) swap(grades, j, j+1) Note that the index j only goes up to num-2, since then j+1 will be num-1, the last element in the array.

Bubble Sort (cont'd) Again, we must do this num times (actually, num-1 times, since if all the elements but the last are in the right place, the last one must be too). After each pass, the next largest element is in the right place at the end of the array, so we don't have to go as far each time, i.e., the inner loop can end one earlier.

Bubble Sort (cont'd) for(int i=0; i<num-1; i++) for(j=0; j<num-1-i; j++) if(grades[j] > grades[j+1]) swap(grades, j, j+1)

Improved Bubblesort We can improve upon the na i ve bubblesort by checking if we do any swapping at all. If no swaps are done, then the array is in order and we can stop (after a pass that verifies that no swaps are done)

Advanced Bubblesort for(int i = 0; i < num-1; i++) { boolean swapped = false; for(int j = 0; j < num-1-i; j++) { if(grades[j] > grades[j+1]) { swap(grades, j, j+1); swapped = true; } if(!swapped) break; }

Insertion Sort Another sort that is commonly used to sort cards is as follows: Suppose that we have a hand of cards that is already in order. We can add a card by comparing the card to the last card in our hand, and if the last card is bigger, slide it to the right a bit, and then look at the next-to-last card. Slide it over if it's bigger. We stop when we come to a card that's smaller, or we run out of cards. We insert the new card in the empty slot.

Insertion Sort To insert one card, t, into a hand that is already in order, a[0..i-1], we do: while(i > 0 && a[i-1] > t) { a[i] = a[i-1];// slide one card over i--; // move to the next card } a[i] = t; // insert t Note that we have to check we haven't run out of cards (i > 0) before we compare the last card to t.

Insertion Sort (cont'd) To sort the whole hand, we need another loop to insert all the cards: for(int j=1; j<num-1; j++) { int t = a[j], i = j; while(i > 0 && a[i-i] > t) { a[i] = a[i-1]; i--; } a[i] = t; }