'Is there any reason to keep array length -1 in iterations of a loop using arrays?
private static void SortArray(List<int> nums)
{
int buffer = 0;
for(int i = 0; i < nums.Count - 1; i++)
{
for(int j = 0; j < nums.Count - 1; j++)
{
if(nums[j] < nums[j + 1])
{
buffer = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = buffer;
}
}
}
}
private static bool IsPalindrome(string word)
{
int j = word.Length - 1;
for (int i = 0; i < word.Length - 1 && j >= 0 && word[i] == word[j]; i++, j--);
return j == 0;
}
The two code above are simple algo one used to order numbers in an unordered array (bubble sort) and another to find the palindrome by checking the two edges of the array for matching.
Why does it start from n - 1 elements? i don't really understand the concept behind and sorry if this question might have been asked before.. but feels like i still can't get it.
Some other simple algorithms don't use the n - 1 elements concept in the for loop conditions, why is that so ?
So to make it clear, if the length of a string "HelloWorld" is 10, why substracting it to 10 - 1 since it won't cover all the lenght of the string therefore leaving "d" out.
Solution 1:[1]
If you take a look at the code you have lines where you have nums[j+1]. So if you are on the last element of the array those statements would give you a index out of range error. So you loop one less then the size of the array and since you compare against the next element in each iteration, the last element will be sorted correctly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sebastian Greczek |
