Java Array Exercises: Sort a given array of distinct integers where all its numbers are sorted except two numbers
Java Array: Exercise-73 with Solution
Write a Java program to sort a given array of distinct integers where all its numbers are sorted except two numbers.
Example:
Input :
nums1 = { 3, 5, 6, 9, 8, 7 }
nums2 = { 5, 0, 1, 2, 3, 4, -2 }
Output:
After sorting new array becomes: [3, 5, 6, 7, 8, 9]
After sorting new array becomes: [-2, 0, 1, 2, 3, 4, 5]
Sample Solution:
Java Code:
import java.util.Arrays;
class solution
{
private static int [] sort_Array(int[] nums)
{
int x = -1, y = -1;
int prev = nums[0];
for (int i = 1; i < nums.length; i++)
{
if (prev > nums[i])
{
if (x == -1) {
x = i - 1;
y = i;
}
else {
y = i;
}
}
prev = nums[i];
}
swap_nums(nums, x, y);
return nums;
}
private static void swap_nums(int[] a, int i, int j) {
int temp_val = a[i];
a[i] = a[j];
a[j] = temp_val;
}
public static void main(String[] args)
{
int[] nums1 = { 3, 5, 6, 9, 8, 7 };
System.out.println("\nOriginal array: "+Arrays.toString(nums1));
int[] result1 = sort_Array(nums1);
System.out.println("\nAfter sorting new array becomes: "+Arrays.toString(result1));
int[] nums2 = { 5, 0, 1, 2, 3, 4, -2 };
System.out.println("\nOriginal array: "+Arrays.toString(nums2));
int[] result2 = sort_Array(nums2);
System.out.println("\nAfter sorting new array becomes: "+Arrays.toString(result2));
}
}
Sample Output:
Original array: [3, 5, 6, 9, 8, 7] After sorting new array becomes: [3, 5, 6, 7, 8, 9] Original array: [5, 0, 1, 2, 3, 4, -2] After sorting new array becomes: [-2, 0, 1, 2, 3, 4, 5]
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to find and print one continuous subarray (from a given array of integers) that if you only sort the said subarray in ascending order then the entire array will be sorted in ascending order.
Next: Write a Java program to find all triplets equal to a given sum in a unsorted array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework