This week's book giveaway is in the Kotlin forum.We're giving away four copies of Kotlin for Android App Development and have Peter Sommerhoff on-line!See this thread for details.
Win a copy of Kotlin for Android App Development this week in the Kotlin forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Devaka Cooray
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Junilu Lacar
• Paul Clapham
• Knute Snortum
Saloon Keepers:
• Ron McLeod
• Tim Moores
• Stephan van Hulst
• salvin francis
• Carey Brown
Bartenders:
• Tim Holloway
• Frits Walraven
• Ganesh Patekar

# Sorting Arrays and Keeping Count of the Swaps

Greenhorn
Posts: 2
I need to modify modules used in the book that run a bubble sort, selection sort, and insertion sort on an integer array such that each module keeps a count of the number of swaps it makes.

How do I code for this?

Then we have to design an application that uses 3 identical arrays of at least 20 integers. That calls each module on a different array, and display the number swaps made by each algorithm.

Beginner course, Using Programming Logic and Design by Tony Gaddis (3rd Ed.) - Chapter 9

Bartender
Posts: 2212
47
• 1
It is simple. Declare a variable of type int. Whenever a swap occurs increment this variable.

Aundra Thompson
Greenhorn
Posts: 2
Thank you I must have just been having a mental block last night after too many hours studying. Most appreciated!

Marshal
Posts: 62883
203

Pawel Pawlowicz wrote:It is simple. Declare a variable of type int. Whenever a swap occurs increment this variable.

Agree, but for a large array you will suffer an overflow, so use a long instead.

Paweł Baczyński
Bartender
Posts: 2212
47
I agree. AFAIK bubble sort has n^2 worst case complexity. So it might overflow on an array larger than 46340 elements (sqrt(2^31-1)).

Campbell Ritchie
Marshal
Posts: 62883
203
Last time I tried counting bubble sort, I found it used (n² - n) ÷ 2 comparisons.

 All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad: RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database