List In Dart
1: => To replace the smallest number in a Dart list and move it to the first position, you can use the following code:-
void main() {
List<int> a = [3, 5, 2, 8, 6, 10, 9];
// Find the index of the smallest number in the list
int minIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[minIndex]) {
minIndex = i;
}
}
// Swap the smallest number with the number at the first position
int temp = a[0];
a[0] = a[minIndex];
a[minIndex] = temp;
// Print the updated list
print(a);
}
2: =>You can sort a Dart list in ascending and descending order without using a separate function by using the sort method and providing a custom comparison function. Here's an example:
void main() {
List<int> a = [3, 5, 2, 8, 6, 10, 9];
// Sort in ascending order
a.sort((a, b) => a.compareTo(b));
print('Ascending Order: $a');
// Sort in descending order
a.sort((a, b) => b.compareTo(a));
print('Descending Order: $a');
}
3:=> If you want to arrange a list in ascending and descending order without using the sort function, you can implement your own sorting algorithm. One simple sorting algorithm is the Bubble Sort algorithm. Here's an example in Dart:
void bubbleSortAscending(List<int> list) {
int n = list.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (list[j] > list[j + 1]) {
// Swap elements if they are in the wrong order
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
void bubbleSortDescending(List<int> list) {
int n = list.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (list[j] < list[j + 1]) {
// Swap elements if they are in the wrong order
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
void main() {
List<int> a = [3, 5, 2, 8, 6, 10, 9];
// Sort in ascending order using Bubble Sort
bubbleSortAscending(a);
print('Ascending Order: $a');
// Sort in descending order using Bubble Sort
bubbleSortDescending(a);
print('Descending Order: $a');
}
Describe:This example uses the Bubble Sort algorithm to arrange the list in ascending and descending order. The
bubbleSortAscending and
bubbleSortDescending functions are used to perform the sorting. Keep in mind that Bubble
Sort is not the most efficient sorting algorithm for large lists, but it's a simple one for educational purposes.
Thanks for reading the article...
Comments
Post a Comment