bubble sort

class Main {
public static void main(String[] args) {
int[] nums = {5, 8, 3, 2, 1, 22, 15};

for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}

for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
}
class Main {
public static void main(String[] args) {
int[] nums = {5, 8, 3, 2, 1, 22, 15};

for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}

for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
}
in this bubble sort why we need 2 loops? and we used
nums[j]
nums[j]
instead of
nums[i]
nums[i]
3 Replies
JavaBot
JavaBot15mo ago
This post has been reserved for your question.
Hey @Manish Kumar! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Kyo-chan
Kyo-chan15mo ago
Try to visualize how the bubble sort works. The idea is to run through the array, making small values bubble up to the start of the array. And to repeat doing that until the array is sorted So you: - repeat -- running through the array That's a loop of a loop
JavaBot
JavaBot15mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?