Selection sort is a sorting method that finds the smallest element in an unsorted region of an array and places it at the beginning of the array. In the provided array, the method keeps two subarrays:
Algorithm for Selection Sort:
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
nums
, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition.Example:
Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Solution:
class Solution {
public static int[] sortArrayByParity(int[] nums) {
int n = nums.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (nums[j] % 2 == 0 && nums[j] < nums[minIndex] || nums[minIndex] % 2 != 0) {
minIndex = j;
}
}
// swap nums[i] and nums[minIndex]
int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
return nums;
}
}
s
, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them.Example:
Input: s = "cccaaa" Output: "aaaccc" Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. Note that "cacaca" is incorrect, as the same characters must be together.
Solution:
class Solution {
public String frequencySort(String s) {
if (s == null || s.length() == 0) {
return "";
}
int[] freq = new int[256]; // ASCII has 256 characters
for (char c : s.toCharArray()) {
freq[c]++;
}
char[] sorted = new char[s.length()];
int idx = 0;
while (idx < s.length()) {
char maxChar = 0;
int maxFreq = 0;
for (int i = 0; i < 256; i++) {
if (freq[i] > maxFreq) {
maxFreq = freq[i];
maxChar = (char) i;
}
}
while (maxFreq > 0) {
sorted[idx++] = maxChar;
maxFreq--;
}
freq[maxChar] = 0;
}
return new String(sorted);
}
}
Note: also read about Bubble Sort
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…