Book contents
- Frontmatter
- Contents
- Preface
- PART ONE FOUNDATIONS
- PART TWO DATA STRUCTURES
- 9 Abstract Data Types
- 10 Containers as Abstract Data Types
- 11 Stack and Queue
- 12 Application of Stack
- 13 Lists
- 14 Trees, Heaps, and Priority Queues
- 15 Search Trees
- 16 Hashing and Sets
- 17 Association and Dictionary
- 18 Sorting
- Appendix A Unified Modeling Language Notation
- Appendix B Complexity of Algorithms
- Appendix C Installing and Using Foundations Classes
- Index
18 - Sorting
from PART TWO - DATA STRUCTURES
Published online by Cambridge University Press: 05 June 2012
- Frontmatter
- Contents
- Preface
- PART ONE FOUNDATIONS
- PART TWO DATA STRUCTURES
- 9 Abstract Data Types
- 10 Containers as Abstract Data Types
- 11 Stack and Queue
- 12 Application of Stack
- 13 Lists
- 14 Trees, Heaps, and Priority Queues
- 15 Search Trees
- 16 Hashing and Sets
- 17 Association and Dictionary
- 18 Sorting
- Appendix A Unified Modeling Language Notation
- Appendix B Complexity of Algorithms
- Appendix C Installing and Using Foundations Classes
- Index
Summary
Sorting involves rearranging information in some container, usually an array, so that the information is stored from smallest to largest (ascending order) or from largest to smallest (descending order). The need to sort is fundamental. We are interested in finding efficient algorithms to accomplish the task.
We shall assume throughout this chapter that the entities to be sorted are Comparable. That is, they may be compared using the query compareTo.
All the sorting methods are presented as static functions with an array of Comparable as the first parameter and the number of elements to be sorted as the second parameter. Although this represents a departure from the normal pattern of object-oriented class construction, we believe it is justified. As long as the array of elements to be sorted are Comparable the user should not be burdened with having to create an instance of a sorting class in order to rearrange the elements in the array that requires sorting.
Simple and Inefficient Sorting Algorithms
We consider two relatively simple sorting algorithms in this section before turning our attention to more efficient sorting.
Selection Sort
The array is scanned from index 1 to index n and the location of the largest value is obtained. This value is interchanged with the nth value. This assures that the largest value is placed in the rightmost position (index n).
The array is again scanned, this time from index 1 to index n – 1. The location of the largest value is obtained.
- Type
- Chapter
- Information
- Fundamentals of OOP and Data Structures in Java , pp. 427 - 436Publisher: Cambridge University PressPrint publication year: 2000