• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Sorting Arrays and Keeping Count of the Swaps  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 2184
46
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is simple. Declare a variable of type int. Whenever a swap occurs increment this variable.
 
Aundra Thompson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you I must have just been having a mental block last night after too many hours studying. Most appreciated!
 
Marshal
Posts: 60902
190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 2184
46
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 60902
190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Last time I tried counting bubble sort, I found it used (n² - n) ÷ 2 comparisons.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!