need to create a simples sort method for sorting even odd numbers. It is a probl
ID: 3607576 • Letter: N
Question
need to create a simples sort method for sorting even odd numbers. It is a problem from the book Data structures and Algorithms in Java by Robert Lafore. The answers to this book are on this site but this answer waas not complete, looks like they forgot the odd-even method. If you could create the odd even method I would appreciate it
In Java please.
Thanks!
Problem Writing programs that solve the Programming Projects helps to solidify your understanding of the material and demonstrates how the chapter's concepts are applied. (As noted in the Introduction, qualified instructors may obtain completed solutions to the Programming Projects on the publisher's Web site.) Another simple sort is the odd-even sort. The idea is to repeatedly make two passes through the array. On the first pass you look at all the pairs of items, auil and a+1], where j is odd j 1, 3, 5 ...). If their key values are out of order, you swap them. On the second pass you do the same for all the even values (j = 2, 4, 6, ). You do these two passes repeatedly until the array is sorted Replace the bubbleSort) method in bubbleSort.java (Listing 3.1) with an oddEvenSort) method Make sure it works for varying amounts of data. You'll need to figure out how many times to do the two passes The odd-even sort is actually useful in a multiprocessing environment, where a separate processor can operate on each odd pair simultaneously and then on each even pair. Because the odd pairs are independent of each other, each pair can be checked-and swapped, if necessary-by a different processor. This makes for a very fast sort. Step-by-step solutionExplanation / Answer
Please find my code for OddEven Sort:
public class OddEvenSort
{
public static void oddEvenSort(int arr[], int n)
{
boolean isSorted = false; // Initially array is unsorted
while (!isSorted)
{
isSorted = true;
int temp =0;
// Perform Bubble sort on odd indexed element
for (int i=1; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
// Perform Bubble sort on even indexed element
for (int i=0; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
}
return;
}
public static void main (String[] args)
{
int arr[] = {34, 2, 10, -9, 45,12,67,98};
int n = arr.length;
System.out.println("Before Sorting: ");
for (int i=0; i < n; i++)
System.out.print(arr[i] + " ");
oddEvenSort(arr, n);
System.out.println(" After Sorting: ");
for (int i=0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println(" ");
}
}
/*
Sample run:
Before Sorting:
34 2 10 -9 45 12 67 98
After Sorting:
-9 2 10 12 34 45 67 98
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.