Сортировка элементов списка List
В предыдущей части мы познакомились с тем, что из себя представляет универсальный список List<T> , научились создавать такие списки и выводить значения различных элементов списка в консоль. Сегодня разберемся с тем, как сортировать списки List<T> , содержащие различные типы элементов.
Как мы уже знаем, в классе List<T> предусмотрен метод Sort() , который производит сортировку элементов списка с использованием компаратора по умолчанию. Что это означает рассмотрим на примере.
Пример использования метода Sort() для простых типов данных
Создадим список строк и попробуем его отсортировать:
Результат выполнения программы будет следующим:
То есть мы получили ровно то, что и ожидали — все строки с именами отсортировались по алфавиту. Аналогичным образом, метод Sort() сработает и на числах. Однако, если мы попробуем выполнить вот такой код:
то гарантированно получим исключение следующего содержания:
Для элементов списка не был обнаружен компаратор по умолчанию в результате чего мы и получили сообщение об исключении в котором говориться, что хотя бы один элемент списка должен реализовывать интерфейс IComparable .
Пример использования метода Sort() с компаратором по умолчанию для объектов
Попробуем переписать наш предыдущий пример следующим образом:
Здесь наш класс Person реализует интерфейс IComparable и, соответственно, содержит компаратор по умолчанию — метод CompareTo , который возвращает целочисленное значение: -1, 0 или 1. Смысл работы этого метода точно такой же, как и метода Compare у строк. Теперь, когда мы реализовали в классе компаратор по умолчанию, метод Sort у списка будет работать без вызова исключений, а результат будет такой же, как и при сортировке строк.
В методе CompareTo можно реализовывать любую логику сравнения двух объектов — сравнивать объекты не по одному, а по нескольким полям, делать сортировку по возрастанию или убыванию и т.д.
Пример использования перегруженного метода Sort()
Несмотря на то, что реализация интерфейса IComparable классом позволяет создавать любую логику сравнения элементов списка, иногда бывает необходимым производить сортировку иным образом, чем это реализовано в компараторе по умолчанию. И тогда нам на помощь может прийти перегруженный метод Sort() , который в качестве параметра принимает метод реализующий функцию сравнения двух элементов списка. Например, перепишем нашу программы таким образом, чтобы у класса Person появилось поле возраста человека и отсортируем список по этому полю:
При сортировке списка по возрасту мы передали в метод Sort() анонимный метод в котором и произвели сортировку элементов списка по необходимому нам полю, не переписывая при этом компаратор по умолчанию, реализованный в самом классе Person . Результат работы программы будет следующий:
Итого
Сегодня мы научились производить сортировку списков, содержащих различные типы элементов. Реализовали интерфейс IComparable в своем классе и создали компаратор по умолчанию, а также отсортировали список List<T> , используя анонимный метод в качестве параметра метода Sort .
Как отсортировать строки в алфавитном порядке в СИ?
Вот задание, которое я делаю:
Вот программа, которую я написал на данный момент:
Вроде-бы я всё реализовал (скорее всего не очень грамотно), кроме сортировки записей в алфавитном порядке. Я не знаю, правильно ли я сравниваю строки и какой принцип сравнения у них вообще (А > a, б < а, Б > a). подскажите пожалуйста, как всё это работает и как мне отсортировать строки?
Sort string in C++
Organizing or arranging a group of characters in a definite order i.e, ascending or descending based on their ASCII values is known as sorting a string. The output of a sorting program produces a reordered input or its permutation.
Input: orange,
Output: aegnor,
Input: aPPLE,
Output: ELPPa
Here, the output has ‘a’ in the end as its ASCII value is greater than that of the others.
Hence, to sort a string in alphabetical order, make sure that all characters entered are either uppercase or lowercase letters entirely.
As we know, strings are defined as a one-dimensional array of characters in C++ and are used to store text in general. Remember, that the text stored in a variable belonging to the string data type must be enclosed within double quotes “ “
For example: string a[ ] = “ Welcome to StudyMite!” ;
Each character of a string has an ASCII ( American Standard Code for Information Interchange) value which basically encodes characters into an integer ranging from 0 to 127. Example: ASCII value of A is 65, and of small A is 97. You can display the ASCII value of a character by typecasting the character variable to int data type.
Methods to sort a string
Using sorting techniques
There are several sorting techniques one can use to arrange a string in a definite order. Some of them are:
By Bubble Sort:
The simplest sorting algorithm, the bubble sort, compares each pair of adjacent characters and swaps them if they are in the incorrect order until the entire string is sorted. Basically, it pushes the character with the greater ASCII value to the end of the list.
Algorithm:
Step 1: Input a string.
Step 2: Declare a temporary variable for swapping the characters
Step 3: Use a nested for loop to compare the characters and traverse through the string
Step 4: If a variable ‘j’ represents the character in question then if the ASCII value of j is greater than that of j+1, then the characters are swapped using the temporary variable.
Step 5: Continue swapping until both the iterations are complete and the outer loop’s condition evaluates to false. Hence, the string is sorted.
Implementation:
Output:
By Insertion Sort:
This simple sort algorithm picks the characters one by one and places them in the right position. In this algorithm, each iteration removes a character from the input list and places it in the sorted sub-string.
While sorting alphabetically, the algorithm takes the character and places it in the correct position based on the ASCII value.
Algorithm:
Step 1: Input a string.
Step 2: Use a for loop to traverse through the string.
Step 3: Consider the first element to be a sorted sublist.
Step 4: Compare each element with the elements of the sorted sublist
Step 5: Shift all the greater elements to the right.
Step 6: Follow step 4-5 until the end of the string to obtain a sorted one.
Implementation:
Output:
By Quick Sort:
Similar to merge sort, quick sort has a recursive algorithm that uses the divide and conquer technique to arrange the elements in a certain order.
The algorithm does not use extra storage for the sublists and instead uses the technique to split the same list into two with the assistance of the pivot value which is considered to be the first element ideally. However, any element can be chosen.
The partition point is then used to divide the list for subsequent calls to the quick sort.
Algorithm:
Step 1: Input a string.
Step 2: Declare the pivot variable and assign it to the middlemost character of the string.
Step 3: Declare two variables low and high as the lower and upper bounds of the string respectively.
Step 4: Begin the partitioning process using the while loop and swapping elements to split the list into two parts- one with characters larger than the pivot element and the other, smaller.
Step 5: Recursively repeat the algorithm for both halves of the original string to obtain the sorted string.
Implementation:
Output:
Note: The quick sort and merge sort algorithms can only sort non-spaced strings.
Hence, use the bubble, insertion sort algorithms to sort sentences. Or, you can try the next method:
Using Library Function:
You can use the sort function from the Standard template library of C++ by including the header file in your code.
Syntax: sort(first iterator, last iterator),
where the first and last iterators are the starting and ending index of the string respectively.
Using this in-built function is fairly easier and faster to perform as compared to writing your own code.
However, since the provided sort( ) function also uses the quick sort algorithm to sort the string, only non-spaced strings can be sorted using this function.
Implementation:
Output:
As you can see, the program only sorts the first word and ends execution once a ‘null’ character is encountered, hence leaving the second word entirely. Simply put, the quicksort algorithm does not sort a string of words in alphabetical order.
So, above were some methods to sort a string in alphabetical order. Note that you can always create your own functions to carry out operations but a thorough and strong understanding of the basic sorting algorithms can elevate your code to the next level in terms of optimization.
Как сделать сортировку по алфавиту на c++
ты бы хоть сказал что тебе сортировать надо: массив символов, строк .
Здесь например есть наводка как легко можно отсортеровать массив символов:
http://forum.codenet.ru/showthread.php?s=&threadid=31754
Мне нужно сортировать массив строк,прога работает но нужно добавить сортировку.
сбрасывай что есть
не забудь использовать тэги [color=blue][ code ][ /code ][/color]
Вот и само условие задачи:
Имеется информация о пациентах поликлиники: фамилия, инициалы, дата рождения, адрес, основное заболевание, дата последнего посещения лечащего врача. Вычислить количество больных диабетом и вывести в алфавитном порядке сведения о больных диабетом, не посещавших лечащего врача более трех месяцев. Поиск больных, сортировку оформить в виде функций.