Dart Program to Implement Insertion Sort

Dart Program to Implement Insertion Sort

Insertion Sort is a simple yet powerful sorting algorithm, perfect for beginners learning programming in Dart. It works by building a sorted portion of the list one element at a time. Each new element is compared with the sorted portion and inserted into its correct position. Though not the most efficient for large datasets, it is intuitive and helps learners grasp the fundamental concepts of sorting and comparisons.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Learning Insertion Sort is useful because sorting is a common operation in programming. From organizing student scores to arranging dates or even complex objects, understanding how data can be ordered efficiently is essential. Practicing Insertion Sort in Dart also helps beginners get comfortable with loops, array manipulation, and algorithmic thinking in a structured and approachable way.

Program 1: Basic Insertion Sort Using Loops

This program demonstrates the standard approach to Insertion Sort in Dart. It inserts each element into its proper position within the sorted portion of the list.

void insertionSort(List<int> arr) {

  for (int i = 1; i < arr.length; i++) {

    int key = arr[i];
    int j = i - 1;

    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = key;

  }

}

void main() {

  List<int> numbers = [12, 11, 13, 5, 6];

  insertionSort(numbers);

  print("Sorted array: $numbers");

}

In this program, the outer loop selects the element to insert, while the inner loop shifts larger elements to make space. Beginners can visualize how the list gradually becomes sorted with each pass.

Program 2: Insertion Sort in Descending Order

By adjusting the comparison logic, Insertion Sort can sort numbers from largest to smallest.

void insertionSortDescending(List<int> arr) {

  for (int i = 1; i < arr.length; i++) {

    int key = arr[i];
    int j = i - 1;

    while (j >= 0 && arr[j] < key) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = key;

  }

}

void main() {

  List<int> numbers = [4, 2, 9, 1, 5];

  insertionSortDescending(numbers);

  print("Descending order: $numbers");

}

This example teaches beginners how a small change in logic—> vs <—can completely reverse the order of a sorted list. Sorting in descending order is useful in scenarios like ranking scores or arranging products by price.

Program 3: Recursive Insertion Sort

Insertion Sort can also be implemented recursively. Each recursive call sorts the first n-1 elements, then inserts the last element into the correct position.

void recursiveInsertionSort(List<int> arr, int n) {

  if (n <= 1) return;

  recursiveInsertionSort(arr, n - 1);

  int last = arr[n - 1];
  int j = n - 2;

  while (j >= 0 && arr[j] > last) {
    arr[j + 1] = arr[j];
    j--;
  }

  arr[j + 1] = last;

}

void main() {

  List<int> numbers = [20, 12, 11, 15, 10];

  recursiveInsertionSort(numbers, numbers.length);

  print("Sorted array (recursive): $numbers");

}

Recursive implementations help beginners understand recursion, a key concept in programming. It demonstrates breaking a problem into smaller subproblems while maintaining the sorting logic.

Program 4: Insertion Sort with a Comparator Function

Using a comparator function allows more flexibility in sorting. You can define custom rules for ordering elements.

void insertionSortWithComparator(List<int> arr, bool Function(int, int) compare) {

  for (int i = 1; i < arr.length; i++) {

    int key = arr[i];
    int j = i - 1;

    while (j >= 0 && compare(key, arr[j])) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = key;

  }

}

void main() {

  List<int> numbers = [7, 3, 5, 1, 9];

  insertionSortWithComparator(numbers, (a, b) => a < b);

  print("Sorted using comparator: $numbers");

}

This approach is useful for beginners who want to sort based on custom rules, such as absolute values or object properties, without modifying the core logic.

Program 5: Insertion Sort for Objects

Insertion Sort can also sort complex objects based on attributes. This example sorts a list of Person objects by age.

class Person {

  String name;
  int age;

  Person(this.name, this.age);

  @override
  String toString() => "$name ($age)";

}

void insertionSortObjects(List<Person> arr, int Function(Person, Person) compare) {

  for (int i = 1; i < arr.length; i++) {

    Person key = arr[i];
    int j = i - 1;

    while (j >= 0 && compare(key, arr[j]) < 0) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = key;

  }

}

void main() {

  List<Person> people = [Person("Edward", 25), Person("Samantha", 20), Person("Lucia", 30)];

  insertionSortObjects(people, (a, b) => a.age - b.age);

  print("Sorted by age: $people");

}

Sorting objects shows beginners how to apply algorithmic thinking to real-world data. It combines understanding of loops, comparisons, and object-oriented programming.

Frequently Asked Questions (FAQ)

Here are some common questions beginners have about Insertion Sort in Dart:

Q1: Is Insertion Sort efficient for large datasets?
Insertion Sort has a time complexity of O(n²). It’s best suited for small arrays or nearly sorted data. For larger datasets, consider Quick Sort or Merge Sort.

Q2: Can Insertion Sort handle objects?
Yes. Using a comparator function or attribute-based comparison, you can sort objects like classes or maps.

Q3: Why use recursion in Insertion Sort?
Recursion helps learners understand breaking problems into smaller subproblems. Though iterative solutions are generally more practical, recursion strengthens algorithmic thinking.

Q4: Can I sort in descending order?
Absolutely. Adjust the comparison logic in the while loop to reverse the sorting order.

Q5: What is the benefit of using a comparator?
Comparator functions make the algorithm flexible, enabling sorting based on custom criteria without changing the core logic.

Conclusion

Insertion Sort is an excellent starting point for learning sorting algorithms in Dart. By exploring variations like ascending, descending, recursive, comparator-based, and object-based implementations, beginners develop a deeper understanding of programming fundamentals. Practicing these programs helps learners become comfortable with arrays, loops, comparisons, and algorithmic thinking. The best way to master Insertion Sort is to experiment with different datasets and observe how each element finds its correct position step by step—a truly rewarding learning experience.

Scroll to Top