1 Sorting Arrays Chapter 14. 2 Agenda Review of Arrays  Sorting Arrays Bubble Sort Selection Sort Finding the smallest element in array Multidimensional.

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
Understanding the Need for Sorting Records
Chapter 9: Advanced Array Manipulation
Math 130 Introduction to Computing Sorting Lecture # 17 10/11/04 B Smith: Save until Week 15? B Smith: Save until Week 15? B Smith: Skipped Spring 2005?
1 Sorting Animation Chapter Selection Sort Another way of sorting is the selection sort The main idea is to keep finding the smallest (and next.
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
An Introduction to Programming with C++ Fifth Edition
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.
Overview Sort – placing data in an array in some order (usually decreasing or increasing order) Bubble Sort More efficient bubble sort.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Sorting 2 An array a is sorted (ascending order) if: for all i a[i]  a[j] Probably the most well-studied algorithmic problem in Computer Science There.
Searching Arrays. COMP104 Array Sorting & Searching / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and save its.
1 Two-Dimensional Arrays. 2 Can be visualized as consisting m rows, each of n columns Syntax: datatype arrayname [row] [ column] ; Example: int val[3]
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
1 Arrays Chapter 13 Especially read 13.1 – 13.2 Text introduces vectors, which we will not cover, in 13.3.
Chapter 9: Advanced Array Concepts
COP2800 – Computer Programming Using JAVA University of Florida Department of CISE Spring 2013 Lecture 13 – Having Fun with Arrays in Java Webpage:
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
1 Sorting Arrays Chapter Agenda Review of Arrays  Sorting Arrays Bubble Sort Selection Sort Finding the smallest element in array Multidimensional.
Chapter 8 Arrays and Strings
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Introduction to C++ Programming Language Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University,
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
An Introduction to Programming with C++ Fifth Edition Chapter 11 Arrays.
Arrays Multi-dimensional initialize & display Sorting Part II.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
CS1010E Programming Methodology Tutorial 9 Pointers in Arrays & Structures C14,A15,D11,C08,C11,A02.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Computer Science: A Structured Programming Approach Using C1 8-7 Two-Dimensional Arrays The arrays we have discussed so far are known as one- dimensional.
Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Shell Sort. Invented by Donald Shell in 1959, the shell sort is the most efficient of the O(n²) class of sorting algorithms. Of course, the shell sort.
Multi-dimensional Array 1 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
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.
Bubble sort. Quite slow, but simple Principles: Compare 2 numbers next to each other (lets call it current and the one next to it) If the current number.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Computer Skills2 / Scientific Colleges 1 Arrays Topics to cover: Arrays Data Types One-dimensional Arrays Two-dimensional Arrays.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
C++ Arrays.
Multidimensional Arrays
Sorting Arrays Chapter 10
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Presentation transcript:

1 Sorting Arrays Chapter 14

2 Agenda Review of Arrays  Sorting Arrays Bubble Sort Selection Sort Finding the smallest element in array Multidimensional arrays

3 Review Arrays You know how to declare, initialize, process arrays with loops, and pass them to functions: float stuff[10]={3, 4, 6, 8, 2, 1, 0}; for (int k=0; k<9; k++) stuff[k]=stuff[k+1]; Display(stuff, 10);

4 You can also pass one (or more) individual cells of an array to a function: int scores[8]={33, 54, 65, 84, 42, 61, 100, 53}; swap(scores[4], scores[1]); swap(scores[2], scores[7]); Notice a Pattern? void swap(int& x, int& y) { // exchanges the values of x, y: float temp = x; x = y; y = temp; }

5 A small problem…relates to Lab10 p9-11 How do we read a file into an array? If we don’t know how many lines are in file How big an array do we need? How will we keep track of the size of the data set? For example, look at scores.txt online Open your notebooks…this is important!

Any ideas? 6

File into Array Make the array bigger than you will ever need int test_scores[100]; plenty for a class that normally has 20 or 30 students Create and Open the filestream ifstream fin("scores.txt"); then use a counter and loop to read in the file, int k=0; while(fin>>scores[k]) k++; 7

File into array, continued afterwards, grab the value of k and store in variable size, that's our array size now: int size=k; from then on, to display or process the array, loops can use size as the endpoint for (k=0; k<size; k++) cout<<scores[k]; 8

What about moving from array to file? Since you already know the size, it's easy Open an output filestream, and change cout to the filestream name 9

10 Agenda Review of Arrays Sorting Arrays  Bubble Sort Selection Sort Finding the smallest element in array Multidimensional arrays

11 Sorting Arrays Computer scientists often need to sort arrays –Why? Because it’s easier to find things in the array when it is sorted Most data looks better displayed in sorted form (phone books, employee records, Lacrosse games) How can we sort an array? What is the algorithm? A: There are several!!

12 Bubble Sort Bubble sort is one of the simplest sorting algorithms It proceeds through a sequence of iterations, each time moving the next largest item into its correct position On each iteration, it compares each pair of consecutive elements, moving the larger element up

13 Bubble Sort

14 Bubble Sort > 55 ?

15 Bubble Sort swap

16 Bubble Sort

17 Bubble Sort > 55 ?

18 Bubble Sort

19 Bubble Sort > 99 ?

20 Bubble Sort swap

21 Bubble Sort Notice how the data “bubbles up” through the array moving slowly, one bin at a time After N-1 “Passes” or “Sweeps”, the final array is guaranteed to be sorted in ascending order, no matter what input data

22 Bubble Sort #include void print(float a[], int n); //Prints array a void sort(float a[], int n);//Sorts array a void swap(float&, float&);//Swaps a[j] and a[j+1] void main() { float a[] = {55.5, 22.5, 99.9, 66.6, 44.4, 88.8, 33.3, 77.7}; print(a,8); sort(a,8); print(a,8); } void print(float a[], int n) { for (int i=0; i<n-1; i++) cout<< a[i] << ", "; cout << a[n-1] << endl; }

23 Bubble Sort (contd) void sort(float a[], int n) { for (int i=1; i<n; i++) for ( int j=0; j<n-1; j++) if(a[j] > a[j+1]) swap(a[j],a[j+1]); } void swap(float& x, float& y) { float temp; temp=y; y=x; x=temp; }

24 Selection Sort Another way of sorting is the selection sort The main idea is to keep finding the smallest (and next smallest) items in the array And move them into correct position (swap)

25 Selection Sort < smallest? F 55 smallest small_pos 0 k data

26 Selection Sort < smallest? T 55 smallest 0 small_pos k data

27 Selection Sort < smallest? T 22 smallest 1 small_pos k data

28 Selection Sort < smallest? F 22 smallest small_pos 0 k data

29 Selection Sort < smallest? F 22 smallest small_pos 0 k data

30 Selection Sort—SWAP Swap(data[k], data[small_pos]); 22 smallest small_pos 0 k data

31 Selection Sort—Repeat < smallest ? F 55 smallest small_pos 1 k

32 Selection Sort—Finding Smallest After (SIZE-1) iterations of the above, array is sorted The heart of this algorithm is finding the smallest element of the array (and it’s position or index small_pos): smallest=data[0]; // assume 0 th cell small_pos=0; // is smallest for (n=0; n<SIZE; n++) // go thru array if (data[n]<smallest) // if smaller { small_pos=n; //save position smallest=data[n]; // and value }

33 Selection Sort—the whole function void Sort(int data[], int size) { int n, k, small_pos, smallest; for (k=0; k<size-1; k++) {smallest=data[k]; // assume k th cell small_pos=k; // is smallest for (n=k; n<SIZE; n++) if (data[n]<smallest)// if smaller { small_pos=n; //save position smallest=data[n]; // and value } Swap(data[k], data[small_pos]); }

34 Agenda Review of Arrays Sorting Arrays Bubble Sort Selection Sort Finding the smallest element in array Multidimensional arrays 

35 Multidimensional Arrays The arrays we have looked at till now have been one-dimensional They are linear (or sequential) An array of arrays is called a multidimensional array A one-dimensional array of one- dimensional arrays is called a two- dimensional array

36 Multidimensional Arrays An array

37 Multidimensional Arrays An array of arrays COLUMNS ROWS

38 Multidimensional Array Simplest way to define a multi- dimensional array is int matrix[4][6]; This would create a two-dimensional array of type int with 4 rows and 6 columns int matrix[4][6]={0};

39 Multidimensional Arrays An array of arrays COLUMNS ROWS matrix

40 Accessing a 2D Array matrix matrix[2][3]=22; matrix[0][5]=44;

41 Processing a 2D Array w/Loop matrix for(k=0; k<6; k++) matrix[3][k]=k;

42 2D Array Read/Print Example #include void read(int a[][5]); //Read the input into two dimen array a void print(const int a[][5]);//Print array a void main() { int a[3][5]; read(a); print(a); } void read(int a[][5]) { cout << "Enter 15 integers, 5 per row:\n"; for (int i=0; i<3; i++) { for (int j=0; j<5; j++) cin >> a[i][j]; } }

43 2D Array Example (contd) void print(const int a[][5]) { for (int i=0; i<3; i++) { cout << "Row " << i << ": "; for (int j=0; j<5; j++) cout << " " << a[i][j]; cout << endl; } }

44 That’s a wrap ! What we learned today: Sorting Arrays Bubble Sort Selection Sort Multidimensional arrays

45 Go back home proud ! You’re brighter than Ar’ray’ !